<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Source: lib/db.js</title>
    
    
    
    
    
    <meta property="og:title" content=""/>
    <meta property="og:type" content="website"/>
    <meta property="og:image" content=""/>
    
    <meta property="og:url" content=""/>
    
    <script src="scripts/prettify/prettify.js"></script>
    <script src="scripts/prettify/lang-css.js"></script>
    <script src="scripts/jquery.min.js"></script>
    <!--[if lt IE 9]>
      <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/bootstrap.min.css">
    <link type="text/css" rel="stylesheet" href="styles/jaguar.css">
    
    
    <script>
    var config = {"monospaceLinks":true,"cleverLinks":true,"default":{"outputSourceFiles":true},"applicationName":"Node.js MongoDB Driver API","googleAnalytics":"UA-29229787-1","openGraph":{"title":"","type":"website","image":"","site_name":"","url":""},"meta":{"title":"","description":"","keyword":""},"linenums":true};
    </script>
    

    
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

      ga('create', UA-29229787-1, 'auto');
      ga('send', 'pageview');
    </script>    
    
</head>
<body>
<div id="wrap" class="clearfix" style="width:100%;">
    <table style="height:100%;width:100%">
        <tr>
            <td valign='top' width="1px">
                
<div class="navigation">
    <h3 class="applicationName"><a href="index.html">Node.js MongoDB Driver API</a></h3>

    <div class="search">
        <input id="search" type="text" class="form-control input-sm" placeholder="Search Documentations">
    </div>
    <ul class="list">
    
        <li class="item" data-name="Admin">
            <span class="title">
                <a href="Admin.html">Admin</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            <span class="subtitle">Typedefs</span>
            
                <li data-name="Admin~resultCallback"><a href="Admin.html#~resultCallback">resultCallback</a></li>
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Admin#addUser"><a href="Admin.html#addUser">addUser</a></li>
            
                <li data-name="Admin#authenticate"><a href="Admin.html#authenticate">authenticate</a></li>
            
                <li data-name="Admin#buildInfo"><a href="Admin.html#buildInfo">buildInfo</a></li>
            
                <li data-name="Admin#command"><a href="Admin.html#command">command</a></li>
            
                <li data-name="Admin#listDatabases"><a href="Admin.html#listDatabases">listDatabases</a></li>
            
                <li data-name="Admin#logout"><a href="Admin.html#logout">logout</a></li>
            
                <li data-name="Admin#ping"><a href="Admin.html#ping">ping</a></li>
            
                <li data-name="Admin#profilingInfo"><a href="Admin.html#profilingInfo">profilingInfo</a></li>
            
                <li data-name="Admin#profilingLevel"><a href="Admin.html#profilingLevel">profilingLevel</a></li>
            
                <li data-name="Admin#removeUser"><a href="Admin.html#removeUser">removeUser</a></li>
            
                <li data-name="Admin#replSetGetStatus"><a href="Admin.html#replSetGetStatus">replSetGetStatus</a></li>
            
                <li data-name="Admin#serverInfo"><a href="Admin.html#serverInfo">serverInfo</a></li>
            
                <li data-name="Admin#serverStatus"><a href="Admin.html#serverStatus">serverStatus</a></li>
            
                <li data-name="Admin#setProfilingLevel"><a href="Admin.html#setProfilingLevel">setProfilingLevel</a></li>
            
                <li data-name="Admin#validateCollection"><a href="Admin.html#validateCollection">validateCollection</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="AggregationCursor">
            <span class="title">
                <a href="AggregationCursor.html">AggregationCursor</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            <span class="subtitle">Typedefs</span>
            
                <li data-name="AggregationCursor~endCallback"><a href="AggregationCursor.html#~endCallback">endCallback</a></li>
            
                <li data-name="AggregationCursor~iteratorCallback"><a href="AggregationCursor.html#~iteratorCallback">iteratorCallback</a></li>
            
                <li data-name="AggregationCursor~resultCallback"><a href="AggregationCursor.html#~resultCallback">resultCallback</a></li>
            
                <li data-name="AggregationCursor~toArrayResultCallback"><a href="AggregationCursor.html#~toArrayResultCallback">toArrayResultCallback</a></li>
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="AggregationCursor#batchSize"><a href="AggregationCursor.html#batchSize">batchSize</a></li>
            
                <li data-name="AggregationCursor#clone"><a href="AggregationCursor.html#clone">clone</a></li>
            
                <li data-name="AggregationCursor#close"><a href="AggregationCursor.html#close">close</a></li>
            
                <li data-name="AggregationCursor#each"><a href="AggregationCursor.html#each">each</a></li>
            
                <li data-name="AggregationCursor#explain"><a href="AggregationCursor.html#explain">explain</a></li>
            
                <li data-name="AggregationCursor#geoNear"><a href="AggregationCursor.html#geoNear">geoNear</a></li>
            
                <li data-name="AggregationCursor#group"><a href="AggregationCursor.html#group">group</a></li>
            
                <li data-name="AggregationCursor#hasNext"><a href="AggregationCursor.html#hasNext">hasNext</a></li>
            
                <li data-name="AggregationCursor#isClosed"><a href="AggregationCursor.html#isClosed">isClosed</a></li>
            
                <li data-name="AggregationCursor#limit"><a href="AggregationCursor.html#limit">limit</a></li>
            
                <li data-name="AggregationCursor#lookup"><a href="AggregationCursor.html#lookup">lookup</a></li>
            
                <li data-name="AggregationCursor#match"><a href="AggregationCursor.html#match">match</a></li>
            
                <li data-name="AggregationCursor#maxTimeMS"><a href="AggregationCursor.html#maxTimeMS">maxTimeMS</a></li>
            
                <li data-name="AggregationCursor#next"><a href="AggregationCursor.html#next">next</a></li>
            
                <li data-name="AggregationCursor#out"><a href="AggregationCursor.html#out">out</a></li>
            
                <li data-name="AggregationCursor#pause"><a href="AggregationCursor.html#pause">pause</a></li>
            
                <li data-name="AggregationCursor#pipe"><a href="AggregationCursor.html#pipe">pipe</a></li>
            
                <li data-name="AggregationCursor#project"><a href="AggregationCursor.html#project">project</a></li>
            
                <li data-name="AggregationCursor#read"><a href="AggregationCursor.html#read">read</a></li>
            
                <li data-name="AggregationCursor#redact"><a href="AggregationCursor.html#redact">redact</a></li>
            
                <li data-name="AggregationCursor#resume"><a href="AggregationCursor.html#resume">resume</a></li>
            
                <li data-name="AggregationCursor#rewind"><a href="AggregationCursor.html#rewind">rewind</a></li>
            
                <li data-name="AggregationCursor#setEncoding"><a href="AggregationCursor.html#setEncoding">setEncoding</a></li>
            
                <li data-name="AggregationCursor#skip"><a href="AggregationCursor.html#skip">skip</a></li>
            
                <li data-name="AggregationCursor#sort"><a href="AggregationCursor.html#sort">sort</a></li>
            
                <li data-name="AggregationCursor#toArray"><a href="AggregationCursor.html#toArray">toArray</a></li>
            
                <li data-name="AggregationCursor#unpipe"><a href="AggregationCursor.html#unpipe">unpipe</a></li>
            
                <li data-name="AggregationCursor#unshift"><a href="AggregationCursor.html#unshift">unshift</a></li>
            
                <li data-name="AggregationCursor#unwind"><a href="AggregationCursor.html#unwind">unwind</a></li>
            
                <li data-name="AggregationCursor#wrap"><a href="AggregationCursor.html#wrap">wrap</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            <span class="subtitle">Events</span>
            
                <li data-name="AggregationCursor#event:close"><a href="AggregationCursor.html#event:close">close</a></li>
            
                <li data-name="AggregationCursor#event:data"><a href="AggregationCursor.html#event:data">data</a></li>
            
                <li data-name="AggregationCursor#event:end"><a href="AggregationCursor.html#event:end">end</a></li>
            
                <li data-name="AggregationCursor#event:readable"><a href="AggregationCursor.html#event:readable">readable</a></li>
            
            </ul>
        </li>
    
        <li class="item" data-name="Binary">
            <span class="title">
                <a href="Binary.html">Binary</a>
                
            </span>
            <ul class="members itemMembers">
            
            <span class="subtitle">Members</span>
            
                <li data-name="Binary.SUBTYPE_BYTE_ARRAY"><a href="Binary.html#.SUBTYPE_BYTE_ARRAY">SUBTYPE_BYTE_ARRAY</a></li>
            
                <li data-name="Binary.SUBTYPE_DEFAULT"><a href="Binary.html#.SUBTYPE_DEFAULT">SUBTYPE_DEFAULT</a></li>
            
                <li data-name="Binary.SUBTYPE_FUNCTION"><a href="Binary.html#.SUBTYPE_FUNCTION">SUBTYPE_FUNCTION</a></li>
            
                <li data-name="Binary.SUBTYPE_MD5"><a href="Binary.html#.SUBTYPE_MD5">SUBTYPE_MD5</a></li>
            
                <li data-name="Binary.SUBTYPE_USER_DEFINED"><a href="Binary.html#.SUBTYPE_USER_DEFINED">SUBTYPE_USER_DEFINED</a></li>
            
                <li data-name="Binary.SUBTYPE_UUID"><a href="Binary.html#.SUBTYPE_UUID">SUBTYPE_UUID</a></li>
            
                <li data-name="Binary.SUBTYPE_UUID_OLD"><a href="Binary.html#.SUBTYPE_UUID_OLD">SUBTYPE_UUID_OLD</a></li>
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Binary#length"><a href="Binary.html#length">length</a></li>
            
                <li data-name="Binary#put"><a href="Binary.html#put">put</a></li>
            
                <li data-name="Binary#read"><a href="Binary.html#read">read</a></li>
            
                <li data-name="Binary#value"><a href="Binary.html#value">value</a></li>
            
                <li data-name="Binary#write"><a href="Binary.html#write">write</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="BSONRegExp">
            <span class="title">
                <a href="BSONRegExp.html">BSONRegExp</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="BulkWriteResult">
            <span class="title">
                <a href="BulkWriteResult.html">BulkWriteResult</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="BulkWriteResult#getInsertedIds"><a href="BulkWriteResult.html#getInsertedIds">getInsertedIds</a></li>
            
                <li data-name="BulkWriteResult#getLastOp"><a href="BulkWriteResult.html#getLastOp">getLastOp</a></li>
            
                <li data-name="BulkWriteResult#getRawResponse"><a href="BulkWriteResult.html#getRawResponse">getRawResponse</a></li>
            
                <li data-name="BulkWriteResult#getUpsertedIdAt"><a href="BulkWriteResult.html#getUpsertedIdAt">getUpsertedIdAt</a></li>
            
                <li data-name="BulkWriteResult#getUpsertedIds"><a href="BulkWriteResult.html#getUpsertedIds">getUpsertedIds</a></li>
            
                <li data-name="BulkWriteResult#getWriteConcernError"><a href="BulkWriteResult.html#getWriteConcernError">getWriteConcernError</a></li>
            
                <li data-name="BulkWriteResult#getWriteErrorAt"><a href="BulkWriteResult.html#getWriteErrorAt">getWriteErrorAt</a></li>
            
                <li data-name="BulkWriteResult#getWriteErrorCount"><a href="BulkWriteResult.html#getWriteErrorCount">getWriteErrorCount</a></li>
            
                <li data-name="BulkWriteResult#getWriteErrors"><a href="BulkWriteResult.html#getWriteErrors">getWriteErrors</a></li>
            
                <li data-name="BulkWriteResult#hasWriteErrors"><a href="BulkWriteResult.html#hasWriteErrors">hasWriteErrors</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="Code">
            <span class="title">
                <a href="Code.html">Code</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="Collection">
            <span class="title">
                <a href="Collection.html">Collection</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            <span class="subtitle">Typedefs</span>
            
                <li data-name="Collection~bulkWriteOpCallback"><a href="Collection.html#~bulkWriteOpCallback">bulkWriteOpCallback</a></li>
            
                <li data-name="Collection~BulkWriteOpResult"><a href="Collection.html#~BulkWriteOpResult">BulkWriteOpResult</a></li>
            
                <li data-name="Collection~collectionResultCallback"><a href="Collection.html#~collectionResultCallback">collectionResultCallback</a></li>
            
                <li data-name="Collection~countCallback"><a href="Collection.html#~countCallback">countCallback</a></li>
            
                <li data-name="Collection~deleteWriteOpCallback"><a href="Collection.html#~deleteWriteOpCallback">deleteWriteOpCallback</a></li>
            
                <li data-name="Collection~deleteWriteOpResult"><a href="Collection.html#~deleteWriteOpResult">deleteWriteOpResult</a></li>
            
                <li data-name="Collection~findAndModifyCallback"><a href="Collection.html#~findAndModifyCallback">findAndModifyCallback</a></li>
            
                <li data-name="Collection~findAndModifyWriteOpResult"><a href="Collection.html#~findAndModifyWriteOpResult">findAndModifyWriteOpResult</a></li>
            
                <li data-name="Collection~insertOneWriteOpCallback"><a href="Collection.html#~insertOneWriteOpCallback">insertOneWriteOpCallback</a></li>
            
                <li data-name="Collection~insertOneWriteOpResult"><a href="Collection.html#~insertOneWriteOpResult">insertOneWriteOpResult</a></li>
            
                <li data-name="Collection~insertWriteOpCallback"><a href="Collection.html#~insertWriteOpCallback">insertWriteOpCallback</a></li>
            
                <li data-name="Collection~insertWriteOpResult"><a href="Collection.html#~insertWriteOpResult">insertWriteOpResult</a></li>
            
                <li data-name="Collection~parallelCollectionScanCallback"><a href="Collection.html#~parallelCollectionScanCallback">parallelCollectionScanCallback</a></li>
            
                <li data-name="Collection~resultCallback"><a href="Collection.html#~resultCallback">resultCallback</a></li>
            
                <li data-name="Collection~updateWriteOpCallback"><a href="Collection.html#~updateWriteOpCallback">updateWriteOpCallback</a></li>
            
                <li data-name="Collection~updateWriteOpResult"><a href="Collection.html#~updateWriteOpResult">updateWriteOpResult</a></li>
            
                <li data-name="Collection~writeOpCallback"><a href="Collection.html#~writeOpCallback">writeOpCallback</a></li>
            
                <li data-name="Collection~WriteOpResult"><a href="Collection.html#~WriteOpResult">WriteOpResult</a></li>
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Collection#aggregate"><a href="Collection.html#aggregate">aggregate</a></li>
            
                <li data-name="Collection#bulkWrite"><a href="Collection.html#bulkWrite">bulkWrite</a></li>
            
                <li data-name="Collection#count"><a href="Collection.html#count">count</a></li>
            
                <li data-name="Collection#createIndex"><a href="Collection.html#createIndex">createIndex</a></li>
            
                <li data-name="Collection#createIndexes"><a href="Collection.html#createIndexes">createIndexes</a></li>
            
                <li data-name="Collection#deleteMany"><a href="Collection.html#deleteMany">deleteMany</a></li>
            
                <li data-name="Collection#deleteOne"><a href="Collection.html#deleteOne">deleteOne</a></li>
            
                <li data-name="Collection#distinct"><a href="Collection.html#distinct">distinct</a></li>
            
                <li data-name="Collection#drop"><a href="Collection.html#drop">drop</a></li>
            
                <li data-name="Collection#dropAllIndexes"><a href="Collection.html#dropAllIndexes">dropAllIndexes</a></li>
            
                <li data-name="Collection#dropIndex"><a href="Collection.html#dropIndex">dropIndex</a></li>
            
                <li data-name="Collection#dropIndexes"><a href="Collection.html#dropIndexes">dropIndexes</a></li>
            
                <li data-name="Collection#ensureIndex"><a href="Collection.html#ensureIndex">ensureIndex</a></li>
            
                <li data-name="Collection#find"><a href="Collection.html#find">find</a></li>
            
                <li data-name="Collection#findAndModify"><a href="Collection.html#findAndModify">findAndModify</a></li>
            
                <li data-name="Collection#findAndRemove"><a href="Collection.html#findAndRemove">findAndRemove</a></li>
            
                <li data-name="Collection#findOne"><a href="Collection.html#findOne">findOne</a></li>
            
                <li data-name="Collection#findOneAndDelete"><a href="Collection.html#findOneAndDelete">findOneAndDelete</a></li>
            
                <li data-name="Collection#findOneAndReplace"><a href="Collection.html#findOneAndReplace">findOneAndReplace</a></li>
            
                <li data-name="Collection#findOneAndUpdate"><a href="Collection.html#findOneAndUpdate">findOneAndUpdate</a></li>
            
                <li data-name="Collection#geoHaystackSearch"><a href="Collection.html#geoHaystackSearch">geoHaystackSearch</a></li>
            
                <li data-name="Collection#geoNear"><a href="Collection.html#geoNear">geoNear</a></li>
            
                <li data-name="Collection#group"><a href="Collection.html#group">group</a></li>
            
                <li data-name="Collection#indexes"><a href="Collection.html#indexes">indexes</a></li>
            
                <li data-name="Collection#indexExists"><a href="Collection.html#indexExists">indexExists</a></li>
            
                <li data-name="Collection#indexInformation"><a href="Collection.html#indexInformation">indexInformation</a></li>
            
                <li data-name="Collection#initializeOrderedBulkOp"><a href="Collection.html#initializeOrderedBulkOp">initializeOrderedBulkOp</a></li>
            
                <li data-name="Collection#initializeUnorderedBulkOp"><a href="Collection.html#initializeUnorderedBulkOp">initializeUnorderedBulkOp</a></li>
            
                <li data-name="Collection#insert"><a href="Collection.html#insert">insert</a></li>
            
                <li data-name="Collection#insertMany"><a href="Collection.html#insertMany">insertMany</a></li>
            
                <li data-name="Collection#insertOne"><a href="Collection.html#insertOne">insertOne</a></li>
            
                <li data-name="Collection#isCapped"><a href="Collection.html#isCapped">isCapped</a></li>
            
                <li data-name="Collection#listIndexes"><a href="Collection.html#listIndexes">listIndexes</a></li>
            
                <li data-name="Collection#mapReduce"><a href="Collection.html#mapReduce">mapReduce</a></li>
            
                <li data-name="Collection#options"><a href="Collection.html#options">options</a></li>
            
                <li data-name="Collection#parallelCollectionScan"><a href="Collection.html#parallelCollectionScan">parallelCollectionScan</a></li>
            
                <li data-name="Collection#reIndex"><a href="Collection.html#reIndex">reIndex</a></li>
            
                <li data-name="Collection#remove"><a href="Collection.html#remove">remove</a></li>
            
                <li data-name="Collection#rename"><a href="Collection.html#rename">rename</a></li>
            
                <li data-name="Collection#replaceOne"><a href="Collection.html#replaceOne">replaceOne</a></li>
            
                <li data-name="Collection#save"><a href="Collection.html#save">save</a></li>
            
                <li data-name="Collection#stats"><a href="Collection.html#stats">stats</a></li>
            
                <li data-name="Collection#update"><a href="Collection.html#update">update</a></li>
            
                <li data-name="Collection#updateMany"><a href="Collection.html#updateMany">updateMany</a></li>
            
                <li data-name="Collection#updateOne"><a href="Collection.html#updateOne">updateOne</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="CommandCursor">
            <span class="title">
                <a href="CommandCursor.html">CommandCursor</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            <span class="subtitle">Typedefs</span>
            
                <li data-name="CommandCursor~endCallback"><a href="CommandCursor.html#~endCallback">endCallback</a></li>
            
                <li data-name="CommandCursor~iteratorCallback"><a href="CommandCursor.html#~iteratorCallback">iteratorCallback</a></li>
            
                <li data-name="CommandCursor~resultCallback"><a href="CommandCursor.html#~resultCallback">resultCallback</a></li>
            
                <li data-name="CommandCursor~toArrayResultCallback"><a href="CommandCursor.html#~toArrayResultCallback">toArrayResultCallback</a></li>
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="CommandCursor#batchSize"><a href="CommandCursor.html#batchSize">batchSize</a></li>
            
                <li data-name="CommandCursor#clone"><a href="CommandCursor.html#clone">clone</a></li>
            
                <li data-name="CommandCursor#close"><a href="CommandCursor.html#close">close</a></li>
            
                <li data-name="CommandCursor#each"><a href="CommandCursor.html#each">each</a></li>
            
                <li data-name="CommandCursor#hasNext"><a href="CommandCursor.html#hasNext">hasNext</a></li>
            
                <li data-name="CommandCursor#isClosed"><a href="CommandCursor.html#isClosed">isClosed</a></li>
            
                <li data-name="CommandCursor#maxTimeMS"><a href="CommandCursor.html#maxTimeMS">maxTimeMS</a></li>
            
                <li data-name="CommandCursor#next"><a href="CommandCursor.html#next">next</a></li>
            
                <li data-name="CommandCursor#pause"><a href="CommandCursor.html#pause">pause</a></li>
            
                <li data-name="CommandCursor#pipe"><a href="CommandCursor.html#pipe">pipe</a></li>
            
                <li data-name="CommandCursor#read"><a href="CommandCursor.html#read">read</a></li>
            
                <li data-name="CommandCursor#resume"><a href="CommandCursor.html#resume">resume</a></li>
            
                <li data-name="CommandCursor#rewind"><a href="CommandCursor.html#rewind">rewind</a></li>
            
                <li data-name="CommandCursor#setEncoding"><a href="CommandCursor.html#setEncoding">setEncoding</a></li>
            
                <li data-name="CommandCursor#setReadPreference"><a href="CommandCursor.html#setReadPreference">setReadPreference</a></li>
            
                <li data-name="CommandCursor#toArray"><a href="CommandCursor.html#toArray">toArray</a></li>
            
                <li data-name="CommandCursor#unpipe"><a href="CommandCursor.html#unpipe">unpipe</a></li>
            
                <li data-name="CommandCursor#unshift"><a href="CommandCursor.html#unshift">unshift</a></li>
            
                <li data-name="CommandCursor#wrap"><a href="CommandCursor.html#wrap">wrap</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            <span class="subtitle">Events</span>
            
                <li data-name="CommandCursor#event:close"><a href="CommandCursor.html#event:close">close</a></li>
            
                <li data-name="CommandCursor#event:data"><a href="CommandCursor.html#event:data">data</a></li>
            
                <li data-name="CommandCursor#event:end"><a href="CommandCursor.html#event:end">end</a></li>
            
                <li data-name="CommandCursor#event:readable"><a href="CommandCursor.html#event:readable">readable</a></li>
            
            </ul>
        </li>
    
        <li class="item" data-name="Cursor">
            <span class="title">
                <a href="Cursor.html">Cursor</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            <span class="subtitle">Typedefs</span>
            
                <li data-name="Cursor~countResultCallback"><a href="Cursor.html#~countResultCallback">countResultCallback</a></li>
            
                <li data-name="Cursor~endCallback"><a href="Cursor.html#~endCallback">endCallback</a></li>
            
                <li data-name="Cursor~iteratorCallback"><a href="Cursor.html#~iteratorCallback">iteratorCallback</a></li>
            
                <li data-name="Cursor~resultCallback"><a href="Cursor.html#~resultCallback">resultCallback</a></li>
            
                <li data-name="Cursor~toArrayResultCallback"><a href="Cursor.html#~toArrayResultCallback">toArrayResultCallback</a></li>
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Cursor#addCursorFlag"><a href="Cursor.html#addCursorFlag">addCursorFlag</a></li>
            
                <li data-name="Cursor#addQueryModifier"><a href="Cursor.html#addQueryModifier">addQueryModifier</a></li>
            
                <li data-name="Cursor#batchSize"><a href="Cursor.html#batchSize">batchSize</a></li>
            
                <li data-name="Cursor#clone"><a href="Cursor.html#clone">clone</a></li>
            
                <li data-name="Cursor#close"><a href="Cursor.html#close">close</a></li>
            
                <li data-name="Cursor#collation"><a href="Cursor.html#collation">collation</a></li>
            
                <li data-name="Cursor#comment"><a href="Cursor.html#comment">comment</a></li>
            
                <li data-name="Cursor#count"><a href="Cursor.html#count">count</a></li>
            
                <li data-name="Cursor#each"><a href="Cursor.html#each">each</a></li>
            
                <li data-name="Cursor#explain"><a href="Cursor.html#explain">explain</a></li>
            
                <li data-name="Cursor#filter"><a href="Cursor.html#filter">filter</a></li>
            
                <li data-name="Cursor#forEach"><a href="Cursor.html#forEach">forEach</a></li>
            
                <li data-name="Cursor#hasNext"><a href="Cursor.html#hasNext">hasNext</a></li>
            
                <li data-name="Cursor#hint"><a href="Cursor.html#hint">hint</a></li>
            
                <li data-name="Cursor#isClosed"><a href="Cursor.html#isClosed">isClosed</a></li>
            
                <li data-name="Cursor#limit"><a href="Cursor.html#limit">limit</a></li>
            
                <li data-name="Cursor#map"><a href="Cursor.html#map">map</a></li>
            
                <li data-name="Cursor#max"><a href="Cursor.html#max">max</a></li>
            
                <li data-name="Cursor#maxAwaitTimeMS"><a href="Cursor.html#maxAwaitTimeMS">maxAwaitTimeMS</a></li>
            
                <li data-name="Cursor#maxScan"><a href="Cursor.html#maxScan">maxScan</a></li>
            
                <li data-name="Cursor#maxTimeMS"><a href="Cursor.html#maxTimeMS">maxTimeMS</a></li>
            
                <li data-name="Cursor#min"><a href="Cursor.html#min">min</a></li>
            
                <li data-name="Cursor#next"><a href="Cursor.html#next">next</a></li>
            
                <li data-name="Cursor#nextObject"><a href="Cursor.html#nextObject">nextObject</a></li>
            
                <li data-name="Cursor#pause"><a href="Cursor.html#pause">pause</a></li>
            
                <li data-name="Cursor#pipe"><a href="Cursor.html#pipe">pipe</a></li>
            
                <li data-name="Cursor#project"><a href="Cursor.html#project">project</a></li>
            
                <li data-name="Cursor#read"><a href="Cursor.html#read">read</a></li>
            
                <li data-name="Cursor#resume"><a href="Cursor.html#resume">resume</a></li>
            
                <li data-name="Cursor#returnKey"><a href="Cursor.html#returnKey">returnKey</a></li>
            
                <li data-name="Cursor#rewind"><a href="Cursor.html#rewind">rewind</a></li>
            
                <li data-name="Cursor#setCursorOption"><a href="Cursor.html#setCursorOption">setCursorOption</a></li>
            
                <li data-name="Cursor#setEncoding"><a href="Cursor.html#setEncoding">setEncoding</a></li>
            
                <li data-name="Cursor#setReadPreference"><a href="Cursor.html#setReadPreference">setReadPreference</a></li>
            
                <li data-name="Cursor#showRecordId"><a href="Cursor.html#showRecordId">showRecordId</a></li>
            
                <li data-name="Cursor#skip"><a href="Cursor.html#skip">skip</a></li>
            
                <li data-name="Cursor#snapshot"><a href="Cursor.html#snapshot">snapshot</a></li>
            
                <li data-name="Cursor#sort"><a href="Cursor.html#sort">sort</a></li>
            
                <li data-name="Cursor#stream"><a href="Cursor.html#stream">stream</a></li>
            
                <li data-name="Cursor#toArray"><a href="Cursor.html#toArray">toArray</a></li>
            
                <li data-name="Cursor#unpipe"><a href="Cursor.html#unpipe">unpipe</a></li>
            
                <li data-name="Cursor#unshift"><a href="Cursor.html#unshift">unshift</a></li>
            
                <li data-name="Cursor#wrap"><a href="Cursor.html#wrap">wrap</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            <span class="subtitle">Events</span>
            
                <li data-name="Cursor#event:close"><a href="Cursor.html#event:close">close</a></li>
            
                <li data-name="Cursor#event:data"><a href="Cursor.html#event:data">data</a></li>
            
                <li data-name="Cursor#event:end"><a href="Cursor.html#event:end">end</a></li>
            
                <li data-name="Cursor#event:readable"><a href="Cursor.html#event:readable">readable</a></li>
            
            </ul>
        </li>
    
        <li class="item" data-name="Db">
            <span class="title">
                <a href="Db.html">Db</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            <span class="subtitle">Typedefs</span>
            
                <li data-name="Db~collectionResultCallback"><a href="Db.html#~collectionResultCallback">collectionResultCallback</a></li>
            
                <li data-name="Db~collectionsResultCallback"><a href="Db.html#~collectionsResultCallback">collectionsResultCallback</a></li>
            
                <li data-name="Db~noResultCallback"><a href="Db.html#~noResultCallback">noResultCallback</a></li>
            
                <li data-name="Db~openCallback"><a href="Db.html#~openCallback">openCallback</a></li>
            
                <li data-name="Db~resultCallback"><a href="Db.html#~resultCallback">resultCallback</a></li>
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Db#addUser"><a href="Db.html#addUser">addUser</a></li>
            
                <li data-name="Db#admin"><a href="Db.html#admin">admin</a></li>
            
                <li data-name="Db#authenticate"><a href="Db.html#authenticate">authenticate</a></li>
            
                <li data-name="Db#close"><a href="Db.html#close">close</a></li>
            
                <li data-name="Db#collection"><a href="Db.html#collection">collection</a></li>
            
                <li data-name="Db#collections"><a href="Db.html#collections">collections</a></li>
            
                <li data-name="Db#command"><a href="Db.html#command">command</a></li>
            
                <li data-name="Db#createCollection"><a href="Db.html#createCollection">createCollection</a></li>
            
                <li data-name="Db#createIndex"><a href="Db.html#createIndex">createIndex</a></li>
            
                <li data-name="Db#db"><a href="Db.html#db">db</a></li>
            
                <li data-name="Db#dropCollection"><a href="Db.html#dropCollection">dropCollection</a></li>
            
                <li data-name="Db#dropDatabase"><a href="Db.html#dropDatabase">dropDatabase</a></li>
            
                <li data-name="Db#ensureIndex"><a href="Db.html#ensureIndex">ensureIndex</a></li>
            
                <li data-name="Db#eval"><a href="Db.html#eval">eval</a></li>
            
                <li data-name="Db#executeDbAdminCommand"><a href="Db.html#executeDbAdminCommand">executeDbAdminCommand</a></li>
            
                <li data-name="Db#indexInformation"><a href="Db.html#indexInformation">indexInformation</a></li>
            
                <li data-name="Db#listCollections"><a href="Db.html#listCollections">listCollections</a></li>
            
                <li data-name="Db#logout"><a href="Db.html#logout">logout</a></li>
            
                <li data-name="Db#open"><a href="Db.html#open">open</a></li>
            
                <li data-name="Db#removeUser"><a href="Db.html#removeUser">removeUser</a></li>
            
                <li data-name="Db#renameCollection"><a href="Db.html#renameCollection">renameCollection</a></li>
            
                <li data-name="Db#stats"><a href="Db.html#stats">stats</a></li>
            
                <li data-name="Db#unref"><a href="Db.html#unref">unref</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            <span class="subtitle">Events</span>
            
                <li data-name="Db#event:authenticated"><a href="Db.html#event:authenticated">authenticated</a></li>
            
                <li data-name="Db#event:close"><a href="Db.html#event:close">close</a></li>
            
                <li data-name="Db#event:error"><a href="Db.html#event:error">error</a></li>
            
                <li data-name="Db#event:fullsetup"><a href="Db.html#event:fullsetup">fullsetup</a></li>
            
                <li data-name="Db#event:parseError"><a href="Db.html#event:parseError">parseError</a></li>
            
                <li data-name="Db#event:reconnect"><a href="Db.html#event:reconnect">reconnect</a></li>
            
                <li data-name="Db#event:timeout"><a href="Db.html#event:timeout">timeout</a></li>
            
            </ul>
        </li>
    
        <li class="item" data-name="DBRef">
            <span class="title">
                <a href="DBRef.html">DBRef</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="Decimal128">
            <span class="title">
                <a href="Decimal128.html">Decimal128</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Decimal128#toString"><a href="Decimal128.html#toString">toString</a></li>
            
                <li data-name="Decimal128.fromString"><a href="Decimal128.html#.fromString">fromString</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="Double">
            <span class="title">
                <a href="Double.html">Double</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Double#valueOf"><a href="Double.html#valueOf">valueOf</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="FindOperatorsOrdered">
            <span class="title">
                <a href="FindOperatorsOrdered.html">FindOperatorsOrdered</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="FindOperatorsOrdered#delete"><a href="FindOperatorsOrdered.html#delete">delete</a></li>
            
                <li data-name="FindOperatorsOrdered#deleteOne"><a href="FindOperatorsOrdered.html#deleteOne">deleteOne</a></li>
            
                <li data-name="FindOperatorsOrdered#replaceOne"><a href="FindOperatorsOrdered.html#replaceOne">replaceOne</a></li>
            
                <li data-name="FindOperatorsOrdered#update"><a href="FindOperatorsOrdered.html#update">update</a></li>
            
                <li data-name="FindOperatorsOrdered#updateOne"><a href="FindOperatorsOrdered.html#updateOne">updateOne</a></li>
            
                <li data-name="FindOperatorsOrdered#upsert"><a href="FindOperatorsOrdered.html#upsert">upsert</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="FindOperatorsUnordered">
            <span class="title">
                <a href="FindOperatorsUnordered.html">FindOperatorsUnordered</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="FindOperatorsUnordered#remove"><a href="FindOperatorsUnordered.html#remove">remove</a></li>
            
                <li data-name="FindOperatorsUnordered#removeOne"><a href="FindOperatorsUnordered.html#removeOne">removeOne</a></li>
            
                <li data-name="FindOperatorsUnordered#replaceOne"><a href="FindOperatorsUnordered.html#replaceOne">replaceOne</a></li>
            
                <li data-name="FindOperatorsUnordered#update"><a href="FindOperatorsUnordered.html#update">update</a></li>
            
                <li data-name="FindOperatorsUnordered#updateOne"><a href="FindOperatorsUnordered.html#updateOne">updateOne</a></li>
            
                <li data-name="FindOperatorsUnordered#upsert"><a href="FindOperatorsUnordered.html#upsert">upsert</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="GridFSBucket">
            <span class="title">
                <a href="GridFSBucket.html">GridFSBucket</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            <span class="subtitle">Typedefs</span>
            
                <li data-name="GridFSBucket~errorCallback"><a href="GridFSBucket.html#~errorCallback">errorCallback</a></li>
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="GridFSBucket#delete"><a href="GridFSBucket.html#delete">delete</a></li>
            
                <li data-name="GridFSBucket#drop"><a href="GridFSBucket.html#drop">drop</a></li>
            
                <li data-name="GridFSBucket#find"><a href="GridFSBucket.html#find">find</a></li>
            
                <li data-name="GridFSBucket#openDownloadStream"><a href="GridFSBucket.html#openDownloadStream">openDownloadStream</a></li>
            
                <li data-name="GridFSBucket#openDownloadStreamByName"><a href="GridFSBucket.html#openDownloadStreamByName">openDownloadStreamByName</a></li>
            
                <li data-name="GridFSBucket#openUploadStream"><a href="GridFSBucket.html#openUploadStream">openUploadStream</a></li>
            
                <li data-name="GridFSBucket#openUploadStreamWithId"><a href="GridFSBucket.html#openUploadStreamWithId">openUploadStreamWithId</a></li>
            
                <li data-name="GridFSBucket#rename"><a href="GridFSBucket.html#rename">rename</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            <span class="subtitle">Events</span>
            
                <li data-name="GridFSBucket#event:index"><a href="GridFSBucket.html#event:index">index</a></li>
            
            </ul>
        </li>
    
        <li class="item" data-name="GridFSBucketReadStream">
            <span class="title">
                <a href="GridFSBucketReadStream.html">GridFSBucketReadStream</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="GridFSBucketReadStream#_read"><a href="GridFSBucketReadStream.html#_read">_read</a></li>
            
                <li data-name="GridFSBucketReadStream#abort"><a href="GridFSBucketReadStream.html#abort">abort</a></li>
            
                <li data-name="GridFSBucketReadStream#end"><a href="GridFSBucketReadStream.html#end">end</a></li>
            
                <li data-name="GridFSBucketReadStream#start"><a href="GridFSBucketReadStream.html#start">start</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            <span class="subtitle">Events</span>
            
                <li data-name="GridFSBucketReadStream#event:close"><a href="GridFSBucketReadStream.html#event:close">close</a></li>
            
                <li data-name="GridFSBucketReadStream#event:data"><a href="GridFSBucketReadStream.html#event:data">data</a></li>
            
                <li data-name="GridFSBucketReadStream#event:end"><a href="GridFSBucketReadStream.html#event:end">end</a></li>
            
                <li data-name="GridFSBucketReadStream#event:error"><a href="GridFSBucketReadStream.html#event:error">error</a></li>
            
                <li data-name="GridFSBucketReadStream#event:file"><a href="GridFSBucketReadStream.html#event:file">file</a></li>
            
            </ul>
        </li>
    
        <li class="item" data-name="GridFSBucketWriteStream">
            <span class="title">
                <a href="GridFSBucketWriteStream.html">GridFSBucketWriteStream</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="GridFSBucketWriteStream#abort"><a href="GridFSBucketWriteStream.html#abort">abort</a></li>
            
                <li data-name="GridFSBucketWriteStream#end"><a href="GridFSBucketWriteStream.html#end">end</a></li>
            
                <li data-name="GridFSBucketWriteStream#write"><a href="GridFSBucketWriteStream.html#write">write</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            <span class="subtitle">Events</span>
            
                <li data-name="GridFSBucketWriteStream#event:error"><a href="GridFSBucketWriteStream.html#event:error">error</a></li>
            
                <li data-name="GridFSBucketWriteStream#event:finish"><a href="GridFSBucketWriteStream.html#event:finish">finish</a></li>
            
            </ul>
        </li>
    
        <li class="item" data-name="GridStore">
            <span class="title">
                <a href="GridStore.html">GridStore</a>
                
            </span>
            <ul class="members itemMembers">
            
            <span class="subtitle">Members</span>
            
                <li data-name="GridStore.DEFAULT_CONTENT_TYPE"><a href="GridStore.html#.DEFAULT_CONTENT_TYPE">DEFAULT_CONTENT_TYPE</a></li>
            
                <li data-name="GridStore.DEFAULT_ROOT_COLLECTION"><a href="GridStore.html#.DEFAULT_ROOT_COLLECTION">DEFAULT_ROOT_COLLECTION</a></li>
            
                <li data-name="GridStore.IO_SEEK_CUR"><a href="GridStore.html#.IO_SEEK_CUR">IO_SEEK_CUR</a></li>
            
                <li data-name="GridStore.IO_SEEK_END"><a href="GridStore.html#.IO_SEEK_END">IO_SEEK_END</a></li>
            
                <li data-name="GridStore.IO_SEEK_SET"><a href="GridStore.html#.IO_SEEK_SET">IO_SEEK_SET</a></li>
            
            </ul>
            <ul class="typedefs itemMembers">
            
            <span class="subtitle">Typedefs</span>
            
                <li data-name="GridStore~collectionCallback"><a href="GridStore.html#~collectionCallback">collectionCallback</a></li>
            
                <li data-name="GridStore~gridStoreCallback"><a href="GridStore.html#~gridStoreCallback">gridStoreCallback</a></li>
            
                <li data-name="GridStore~openCallback"><a href="GridStore.html#~openCallback">openCallback</a></li>
            
                <li data-name="GridStore~readCallback"><a href="GridStore.html#~readCallback">readCallback</a></li>
            
                <li data-name="GridStore~readlinesCallback"><a href="GridStore.html#~readlinesCallback">readlinesCallback</a></li>
            
                <li data-name="GridStore~resultCallback"><a href="GridStore.html#~resultCallback">resultCallback</a></li>
            
                <li data-name="GridStore~tellCallback"><a href="GridStore.html#~tellCallback">tellCallback</a></li>
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="GridStore.exist"><a href="GridStore.html#.exist">exist</a></li>
            
                <li data-name="GridStore.list"><a href="GridStore.html#.list">list</a></li>
            
                <li data-name="GridStore.read"><a href="GridStore.html#.read">read</a></li>
            
                <li data-name="GridStore.readlines"><a href="GridStore.html#.readlines">readlines</a></li>
            
                <li data-name="GridStore.unlink"><a href="GridStore.html#.unlink">unlink</a></li>
            
                <li data-name="GridStore#chunkCollection"><a href="GridStore.html#chunkCollection">chunkCollection</a></li>
            
                <li data-name="GridStore#close"><a href="GridStore.html#close">close</a></li>
            
                <li data-name="GridStore#collection"><a href="GridStore.html#collection">collection</a></li>
            
                <li data-name="GridStore#destroy"><a href="GridStore.html#destroy">destroy</a></li>
            
                <li data-name="GridStore#eof"><a href="GridStore.html#eof">eof</a></li>
            
                <li data-name="GridStore#getc"><a href="GridStore.html#getc">getc</a></li>
            
                <li data-name="GridStore#open"><a href="GridStore.html#open">open</a></li>
            
                <li data-name="GridStore#puts"><a href="GridStore.html#puts">puts</a></li>
            
                <li data-name="GridStore#read"><a href="GridStore.html#read">read</a></li>
            
                <li data-name="GridStore#readlines"><a href="GridStore.html#readlines">readlines</a></li>
            
                <li data-name="GridStore#rewind"><a href="GridStore.html#rewind">rewind</a></li>
            
                <li data-name="GridStore#seek"><a href="GridStore.html#seek">seek</a></li>
            
                <li data-name="GridStore#stream"><a href="GridStore.html#stream">stream</a></li>
            
                <li data-name="GridStore#tell"><a href="GridStore.html#tell">tell</a></li>
            
                <li data-name="GridStore#unlink"><a href="GridStore.html#unlink">unlink</a></li>
            
                <li data-name="GridStore#write"><a href="GridStore.html#write">write</a></li>
            
                <li data-name="GridStore#writeFile"><a href="GridStore.html#writeFile">writeFile</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="GridStoreStream">
            <span class="title">
                <a href="GridStoreStream.html">GridStoreStream</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="GridStoreStream#end"><a href="GridStoreStream.html#end">end</a></li>
            
                <li data-name="GridStoreStream#pause"><a href="GridStoreStream.html#pause">pause</a></li>
            
                <li data-name="GridStoreStream#pipe"><a href="GridStoreStream.html#pipe">pipe</a></li>
            
                <li data-name="GridStoreStream#read"><a href="GridStoreStream.html#read">read</a></li>
            
                <li data-name="GridStoreStream#resume"><a href="GridStoreStream.html#resume">resume</a></li>
            
                <li data-name="GridStoreStream#setEncoding"><a href="GridStoreStream.html#setEncoding">setEncoding</a></li>
            
                <li data-name="GridStoreStream#unpipe"><a href="GridStoreStream.html#unpipe">unpipe</a></li>
            
                <li data-name="GridStoreStream#unshift"><a href="GridStoreStream.html#unshift">unshift</a></li>
            
                <li data-name="GridStoreStream#wrap"><a href="GridStoreStream.html#wrap">wrap</a></li>
            
                <li data-name="GridStoreStream#write"><a href="GridStoreStream.html#write">write</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            <span class="subtitle">Events</span>
            
                <li data-name="GridStoreStream#event:close"><a href="GridStoreStream.html#event:close">close</a></li>
            
                <li data-name="GridStoreStream#event:data"><a href="GridStoreStream.html#event:data">data</a></li>
            
                <li data-name="GridStoreStream#event:drain"><a href="GridStoreStream.html#event:drain">drain</a></li>
            
                <li data-name="GridStoreStream#event:end"><a href="GridStoreStream.html#event:end">end</a></li>
            
                <li data-name="GridStoreStream#event:error"><a href="GridStoreStream.html#event:error">error</a></li>
            
                <li data-name="GridStoreStream#event:finish"><a href="GridStoreStream.html#event:finish">finish</a></li>
            
                <li data-name="GridStoreStream#event:pipe"><a href="GridStoreStream.html#event:pipe">pipe</a></li>
            
                <li data-name="GridStoreStream#event:readable"><a href="GridStoreStream.html#event:readable">readable</a></li>
            
                <li data-name="GridStoreStream#event:unpipe"><a href="GridStoreStream.html#event:unpipe">unpipe</a></li>
            
            </ul>
        </li>
    
        <li class="item" data-name="Int32">
            <span class="title">
                <a href="Int32.html">Int32</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Int32#valueOf"><a href="Int32.html#valueOf">valueOf</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="Logger">
            <span class="title">
                <a href="Logger.html">Logger</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Logger.currentLogger"><a href="Logger.html#.currentLogger">currentLogger</a></li>
            
                <li data-name="Logger.filter"><a href="Logger.html#.filter">filter</a></li>
            
                <li data-name="Logger.reset"><a href="Logger.html#.reset">reset</a></li>
            
                <li data-name="Logger.setCurrentLogger"><a href="Logger.html#.setCurrentLogger">setCurrentLogger</a></li>
            
                <li data-name="Logger.setLevel"><a href="Logger.html#.setLevel">setLevel</a></li>
            
                <li data-name="Logger#debug"><a href="Logger.html#debug">debug</a></li>
            
                <li data-name="Logger#error"><a href="Logger.html#error">error</a></li>
            
                <li data-name="Logger#info"><a href="Logger.html#info">info</a></li>
            
                <li data-name="Logger#isDebug"><a href="Logger.html#isDebug">isDebug</a></li>
            
                <li data-name="Logger#isError"><a href="Logger.html#isError">isError</a></li>
            
                <li data-name="Logger#isInfo"><a href="Logger.html#isInfo">isInfo</a></li>
            
                <li data-name="Logger#isWarn"><a href="Logger.html#isWarn">isWarn</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="Long">
            <span class="title">
                <a href="Long.html">Long</a>
                
            </span>
            <ul class="members itemMembers">
            
            <span class="subtitle">Members</span>
            
                <li data-name="Long.MAX_VALUE"><a href="Long.html#.MAX_VALUE">MAX_VALUE</a></li>
            
                <li data-name="Long.MIN_VALUE"><a href="Long.html#.MIN_VALUE">MIN_VALUE</a></li>
            
                <li data-name="Long.NEG_ONE"><a href="Long.html#.NEG_ONE">NEG_ONE</a></li>
            
                <li data-name="Long.ONE"><a href="Long.html#.ONE">ONE</a></li>
            
                <li data-name="Long.ZERO"><a href="Long.html#.ZERO">ZERO</a></li>
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Long.fromBits"><a href="Long.html#.fromBits">fromBits</a></li>
            
                <li data-name="Long.fromInt"><a href="Long.html#.fromInt">fromInt</a></li>
            
                <li data-name="Long.fromNumber"><a href="Long.html#.fromNumber">fromNumber</a></li>
            
                <li data-name="Long.fromString"><a href="Long.html#.fromString">fromString</a></li>
            
                <li data-name="Long#add"><a href="Long.html#add">add</a></li>
            
                <li data-name="Long#and"><a href="Long.html#and">and</a></li>
            
                <li data-name="Long#compare"><a href="Long.html#compare">compare</a></li>
            
                <li data-name="Long#div"><a href="Long.html#div">div</a></li>
            
                <li data-name="Long#equals"><a href="Long.html#equals">equals</a></li>
            
                <li data-name="Long#getHighBits"><a href="Long.html#getHighBits">getHighBits</a></li>
            
                <li data-name="Long#getLowBits"><a href="Long.html#getLowBits">getLowBits</a></li>
            
                <li data-name="Long#getLowBitsUnsigned"><a href="Long.html#getLowBitsUnsigned">getLowBitsUnsigned</a></li>
            
                <li data-name="Long#getNumBitsAbs"><a href="Long.html#getNumBitsAbs">getNumBitsAbs</a></li>
            
                <li data-name="Long#greaterThan"><a href="Long.html#greaterThan">greaterThan</a></li>
            
                <li data-name="Long#greaterThanOrEqual"><a href="Long.html#greaterThanOrEqual">greaterThanOrEqual</a></li>
            
                <li data-name="Long#isNegative"><a href="Long.html#isNegative">isNegative</a></li>
            
                <li data-name="Long#isOdd"><a href="Long.html#isOdd">isOdd</a></li>
            
                <li data-name="Long#isZero"><a href="Long.html#isZero">isZero</a></li>
            
                <li data-name="Long#lessThan"><a href="Long.html#lessThan">lessThan</a></li>
            
                <li data-name="Long#lessThanOrEqual"><a href="Long.html#lessThanOrEqual">lessThanOrEqual</a></li>
            
                <li data-name="Long#modulo"><a href="Long.html#modulo">modulo</a></li>
            
                <li data-name="Long#multiply"><a href="Long.html#multiply">multiply</a></li>
            
                <li data-name="Long#negate"><a href="Long.html#negate">negate</a></li>
            
                <li data-name="Long#not"><a href="Long.html#not">not</a></li>
            
                <li data-name="Long#notEquals"><a href="Long.html#notEquals">notEquals</a></li>
            
                <li data-name="Long#or"><a href="Long.html#or">or</a></li>
            
                <li data-name="Long#shiftLeft"><a href="Long.html#shiftLeft">shiftLeft</a></li>
            
                <li data-name="Long#shiftRight"><a href="Long.html#shiftRight">shiftRight</a></li>
            
                <li data-name="Long#shiftRightUnsigned"><a href="Long.html#shiftRightUnsigned">shiftRightUnsigned</a></li>
            
                <li data-name="Long#subtract"><a href="Long.html#subtract">subtract</a></li>
            
                <li data-name="Long#toInt"><a href="Long.html#toInt">toInt</a></li>
            
                <li data-name="Long#toJSON"><a href="Long.html#toJSON">toJSON</a></li>
            
                <li data-name="Long#toNumber"><a href="Long.html#toNumber">toNumber</a></li>
            
                <li data-name="Long#toString"><a href="Long.html#toString">toString</a></li>
            
                <li data-name="Long#xor"><a href="Long.html#xor">xor</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="MaxKey">
            <span class="title">
                <a href="MaxKey.html">MaxKey</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="MinKey">
            <span class="title">
                <a href="MinKey.html">MinKey</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="MongoClient">
            <span class="title">
                <a href="MongoClient.html">MongoClient</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            <span class="subtitle">Typedefs</span>
            
                <li data-name="MongoClient~connectCallback"><a href="MongoClient.html#~connectCallback">connectCallback</a></li>
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="MongoClient.connect"><a href="MongoClient.html#.connect">connect</a></li>
            
                <li data-name="MongoClient#connect"><a href="MongoClient.html#connect">connect</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="MongoError">
            <span class="title">
                <a href="MongoError.html">MongoError</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="MongoError.create"><a href="MongoError.html#.create">create</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="Mongos">
            <span class="title">
                <a href="Mongos.html">Mongos</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Mongos#connections"><a href="Mongos.html#connections">connections</a></li>
            
                <li data-name="Mongos#unref"><a href="Mongos.html#unref">unref</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            <span class="subtitle">Events</span>
            
                <li data-name="Mongos#event:close"><a href="Mongos.html#event:close">close</a></li>
            
                <li data-name="Mongos#event:connect"><a href="Mongos.html#event:connect">connect</a></li>
            
                <li data-name="Mongos#event:error"><a href="Mongos.html#event:error">error</a></li>
            
                <li data-name="Mongos#event:fullsetup"><a href="Mongos.html#event:fullsetup">fullsetup</a></li>
            
                <li data-name="Mongos#event:ha"><a href="Mongos.html#event:ha">ha</a></li>
            
                <li data-name="Mongos#event:joined"><a href="Mongos.html#event:joined">joined</a></li>
            
                <li data-name="Mongos#event:left"><a href="Mongos.html#event:left">left</a></li>
            
                <li data-name="Mongos#event:open"><a href="Mongos.html#event:open">open</a></li>
            
                <li data-name="Mongos#event:parseError"><a href="Mongos.html#event:parseError">parseError</a></li>
            
                <li data-name="Mongos#event:timeout"><a href="Mongos.html#event:timeout">timeout</a></li>
            
            </ul>
        </li>
    
        <li class="item" data-name="ObjectID">
            <span class="title">
                <a href="ObjectID.html">ObjectID</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="ObjectID.createFromHexString"><a href="ObjectID.html#.createFromHexString">createFromHexString</a></li>
            
                <li data-name="ObjectID.createFromTime"><a href="ObjectID.html#.createFromTime">createFromTime</a></li>
            
                <li data-name="ObjectID.isValid"><a href="ObjectID.html#.isValid">isValid</a></li>
            
                <li data-name="ObjectID#equals"><a href="ObjectID.html#equals">equals</a></li>
            
                <li data-name="ObjectID#generate"><a href="ObjectID.html#generate">generate</a></li>
            
                <li data-name="ObjectID#getTimestamp"><a href="ObjectID.html#getTimestamp">getTimestamp</a></li>
            
                <li data-name="ObjectID#toHexString"><a href="ObjectID.html#toHexString">toHexString</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="OrderedBulkOperation">
            <span class="title">
                <a href="OrderedBulkOperation.html">OrderedBulkOperation</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            <span class="subtitle">Typedefs</span>
            
                <li data-name="OrderedBulkOperation~resultCallback"><a href="OrderedBulkOperation.html#~resultCallback">resultCallback</a></li>
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="OrderedBulkOperation#execute"><a href="OrderedBulkOperation.html#execute">execute</a></li>
            
                <li data-name="OrderedBulkOperation#find"><a href="OrderedBulkOperation.html#find">find</a></li>
            
                <li data-name="OrderedBulkOperation#insert"><a href="OrderedBulkOperation.html#insert">insert</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="ReadPreference">
            <span class="title">
                <a href="ReadPreference.html">ReadPreference</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="ReadPreference.isValid"><a href="ReadPreference.html#.isValid">isValid</a></li>
            
                <li data-name="ReadPreference#isValid"><a href="ReadPreference.html#isValid">isValid</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="ReplSet">
            <span class="title">
                <a href="ReplSet.html">ReplSet</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="ReplSet#connections"><a href="ReplSet.html#connections">connections</a></li>
            
                <li data-name="ReplSet#unref"><a href="ReplSet.html#unref">unref</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            <span class="subtitle">Events</span>
            
                <li data-name="ReplSet#event:close"><a href="ReplSet.html#event:close">close</a></li>
            
                <li data-name="ReplSet#event:connect"><a href="ReplSet.html#event:connect">connect</a></li>
            
                <li data-name="ReplSet#event:error"><a href="ReplSet.html#event:error">error</a></li>
            
                <li data-name="ReplSet#event:fullsetup"><a href="ReplSet.html#event:fullsetup">fullsetup</a></li>
            
                <li data-name="ReplSet#event:ha"><a href="ReplSet.html#event:ha">ha</a></li>
            
                <li data-name="ReplSet#event:joined"><a href="ReplSet.html#event:joined">joined</a></li>
            
                <li data-name="ReplSet#event:left"><a href="ReplSet.html#event:left">left</a></li>
            
                <li data-name="ReplSet#event:open"><a href="ReplSet.html#event:open">open</a></li>
            
                <li data-name="ReplSet#event:parseError"><a href="ReplSet.html#event:parseError">parseError</a></li>
            
                <li data-name="ReplSet#event:timeout"><a href="ReplSet.html#event:timeout">timeout</a></li>
            
            </ul>
        </li>
    
        <li class="item" data-name="Server">
            <span class="title">
                <a href="Server.html">Server</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Server#connections"><a href="Server.html#connections">connections</a></li>
            
                <li data-name="Server#unref"><a href="Server.html#unref">unref</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            <span class="subtitle">Events</span>
            
                <li data-name="Server#event:close"><a href="Server.html#event:close">close</a></li>
            
                <li data-name="Server#event:connect"><a href="Server.html#event:connect">connect</a></li>
            
                <li data-name="Server#event:error"><a href="Server.html#event:error">error</a></li>
            
                <li data-name="Server#event:parseError"><a href="Server.html#event:parseError">parseError</a></li>
            
                <li data-name="Server#event:reconnect"><a href="Server.html#event:reconnect">reconnect</a></li>
            
                <li data-name="Server#event:timeout"><a href="Server.html#event:timeout">timeout</a></li>
            
            </ul>
        </li>
    
        <li class="item" data-name="Symbol">
            <span class="title">
                <a href="Symbol.html">Symbol</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Symbol#valueOf"><a href="Symbol.html#valueOf">valueOf</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="Timestamp">
            <span class="title">
                <a href="Timestamp.html">Timestamp</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="Timestamp#toJSON"><a href="Timestamp.html#toJSON">toJSON</a></li>
            
                <li data-name="Timestamp.fromBits"><a href="Timestamp.html#.fromBits">fromBits</a></li>
            
                <li data-name="Timestamp.fromInt"><a href="Timestamp.html#.fromInt">fromInt</a></li>
            
                <li data-name="Timestamp.fromNumber"><a href="Timestamp.html#.fromNumber">fromNumber</a></li>
            
                <li data-name="Timestamp.fromString"><a href="Timestamp.html#.fromString">fromString</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="UnorderedBulkOperation">
            <span class="title">
                <a href="UnorderedBulkOperation.html">UnorderedBulkOperation</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            <span class="subtitle">Typedefs</span>
            
                <li data-name="UnorderedBulkOperation~resultCallback"><a href="UnorderedBulkOperation.html#~resultCallback">resultCallback</a></li>
            
            </ul>
            <ul class="methods itemMembers">
            
            <span class="subtitle">Methods</span>
            
                <li data-name="UnorderedBulkOperation#execute"><a href="UnorderedBulkOperation.html#execute">execute</a></li>
            
                <li data-name="UnorderedBulkOperation#find"><a href="UnorderedBulkOperation.html#find">find</a></li>
            
                <li data-name="UnorderedBulkOperation#insert"><a href="UnorderedBulkOperation.html#insert">insert</a></li>
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="WriteConcernError">
            <span class="title">
                <a href="WriteConcernError.html">WriteConcernError</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
        <li class="item" data-name="WriteError">
            <span class="title">
                <a href="WriteError.html">WriteError</a>
                
            </span>
            <ul class="members itemMembers">
            
            </ul>
            <ul class="typedefs itemMembers">
            
            </ul>
            <ul class="methods itemMembers">
            
            </ul>
            <ul class="events itemMembers">
            
            </ul>
        </li>
    
    </ul>
</div>
            </td>
            <td valign='top'>        
                <div class="main">
                    <h1 class="page-title" data-filename="lib_db.js.html">Source: lib/db.js</h1>
                    


    
    <section>
        <article>
            <pre class="prettyprint source linenums"><code>"use strict";

var EventEmitter = require('events').EventEmitter
  , authenticate = require('./authenticate')
  , inherits = require('util').inherits
  , getSingleProperty = require('./utils').getSingleProperty
  , shallowClone = require('./utils').shallowClone
  , parseIndexOptions = require('./utils').parseIndexOptions
  , debugOptions = require('./utils').debugOptions
  , CommandCursor = require('./command_cursor')
  , handleCallback = require('./utils').handleCallback
  , filterOptions = require('./utils').filterOptions
  , toError = require('./utils').toError
  , ReadPreference = require('./read_preference')
  , f = require('util').format
  , Admin = require('./admin')
  , Code = require('mongodb-core').BSON.Code
  , CoreReadPreference = require('mongodb-core').ReadPreference
  , MongoError = require('mongodb-core').MongoError
  , ObjectID = require('mongodb-core').ObjectID
  , Define = require('./metadata')
  , Logger = require('mongodb-core').Logger
  , Collection = require('./collection')
  , crypto = require('crypto')
  , mergeOptionsAndWriteConcern = require('./utils').mergeOptionsAndWriteConcern
  , assign = require('./utils').assign;

var debugFields = ['authSource', 'w', 'wtimeout', 'j', 'native_parser', 'forceServerObjectId'
  , 'serializeFunctions', 'raw', 'promoteLongs', 'promoteValues', 'promoteBuffers', 'bufferMaxEntries', 'numberOfRetries', 'retryMiliSeconds'
  , 'readPreference', 'pkFactory', 'parentDb', 'promiseLibrary', 'noListener'];

// Filter out any write concern options
var illegalCommandFields = ['w', 'wtimeout', 'j', 'fsync', 'autoIndexId'
  , 'strict', 'serializeFunctions', 'pkFactory', 'raw', 'readPreference'];

/**
 * @fileOverview The **Db** class is a class that represents a MongoDB Database.
 *
 * @example
 * var MongoClient = require('mongodb').MongoClient,
 *   test = require('assert');
 * // Connection url
 * var url = 'mongodb://localhost:27017/test';
 * // Connect using MongoClient
 * MongoClient.connect(url, function(err, db) {
 *   // Get an additional db
 *   var testDb = db.db('test');
 *   db.close();
 * });
 */

// Allowed parameters
var legalOptionNames = ['w', 'wtimeout', 'fsync', 'j', 'readPreference', 'readPreferenceTags', 'native_parser'
  , 'forceServerObjectId', 'pkFactory', 'serializeFunctions', 'raw', 'bufferMaxEntries', 'authSource'
  , 'ignoreUndefined', 'promoteLongs', 'promiseLibrary', 'readConcern', 'retryMiliSeconds', 'numberOfRetries'
  , 'parentDb', 'noListener', 'loggerLevel', 'logger', 'promoteBuffers', 'promoteLongs', 'promoteValues'];

/**
 * Creates a new Db instance
 * @class
 * @param {string} databaseName The name of the database this instance represents.
 * @param {(Server|ReplSet|Mongos)} topology The server topology for the database.
 * @param {object} [options=null] Optional settings.
 * @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName.
 * @param {(number|string)} [options.w=null] The write concern.
 * @param {number} [options.wtimeout=null] The write concern timeout.
 * @param {boolean} [options.j=false] Specify a journal write concern.
 * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
 * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
 * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields.
 * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
 * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
 * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
 * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
 * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited.
 * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
 * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys.
 * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible
 * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)
 * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)
 * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology.
 * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database
 * @property {string} databaseName The name of the database this instance represents.
 * @property {object} options The options associated with the db instance.
 * @property {boolean} native_parser The current value of the parameter native_parser.
 * @property {boolean} slaveOk The current slaveOk value for the db instance.
 * @property {object} writeConcern The current write concern values.
 * @property {object} topology Access the topology object (single server, replicaset or mongos).
 * @fires Db#close
 * @fires Db#authenticated
 * @fires Db#reconnect
 * @fires Db#error
 * @fires Db#timeout
 * @fires Db#parseError
 * @fires Db#fullsetup
 * @return {Db} a Db instance.
 */
var Db = function(databaseName, topology, options) {
  options = options || {};
  if(!(this instanceof Db)) return new Db(databaseName, topology, options);
  EventEmitter.call(this);
  var self = this;

  // Get the promiseLibrary
  var promiseLibrary = options.promiseLibrary;

  // No promise library selected fall back
  if(!promiseLibrary) {
    promiseLibrary = typeof global.Promise == 'function' ?
      global.Promise : require('es6-promise').Promise;
  }

  // Filter the options
  options = filterOptions(options, legalOptionNames);

  // Ensure we put the promiseLib in the options
  options.promiseLibrary = promiseLibrary;

  // var self = this;  // Internal state of the db object
  this.s = {
    // Database name
      databaseName: databaseName
    // DbCache
    , dbCache: {}
    // Children db's
    , children: []
    // Topology
    , topology: topology
    // Options
    , options: options
    // Logger instance
    , logger: Logger('Db', options)
    // Get the bson parser
    , bson: topology ? topology.bson : null
    // Authsource if any
    , authSource: options.authSource
    // Unpack read preference
    , readPreference: options.readPreference
    // Set buffermaxEntries
    , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : -1
    // Parent db (if chained)
    , parentDb: options.parentDb || null
    // Set up the primary key factory or fallback to ObjectID
    , pkFactory: options.pkFactory || ObjectID
    // Get native parser
    , nativeParser: options.nativeParser || options.native_parser
    // Promise library
    , promiseLibrary: promiseLibrary
    // No listener
    , noListener: typeof options.noListener == 'boolean' ? options.noListener : false
    // ReadConcern
    , readConcern: options.readConcern
  }

  // Ensure we have a valid db name
  validateDatabaseName(self.s.databaseName);

  // Add a read Only property
  getSingleProperty(this, 'serverConfig', self.s.topology);
  getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries);
  getSingleProperty(this, 'databaseName', self.s.databaseName);

  // This is a child db, do not register any listeners
  if(options.parentDb) return;
  if(this.s.noListener) return;

  // Add listeners
  topology.on('error', createListener(self, 'error', self));
  topology.on('timeout', createListener(self, 'timeout', self));
  topology.on('close', createListener(self, 'close', self));
  topology.on('parseError', createListener(self, 'parseError', self));
  topology.once('open', createListener(self, 'open', self));
  topology.once('fullsetup', createListener(self, 'fullsetup', self));
  topology.once('all', createListener(self, 'all', self));
  topology.on('reconnect', createListener(self, 'reconnect', self));
  topology.on('reconnectFailed', createListener(self, 'reconnectFailed', self));
}

inherits(Db, EventEmitter);

var define = Db.define = new Define('Db', Db, false);

// Topology
Object.defineProperty(Db.prototype, 'topology', {
  enumerable:true,
  get: function() { return this.s.topology; }
});

// Options
Object.defineProperty(Db.prototype, 'options', {
  enumerable:true,
  get: function() { return this.s.options; }
});

// slaveOk specified
Object.defineProperty(Db.prototype, 'slaveOk', {
  enumerable:true,
  get: function() {
    if(this.s.options.readPreference != null
      &amp;&amp; (this.s.options.readPreference != 'primary' || this.s.options.readPreference.mode != 'primary')) {
      return true;
    }
    return false;
  }
});

// get the write Concern
Object.defineProperty(Db.prototype, 'writeConcern', {
  enumerable:true,
  get: function() {
    var ops = {};
    if(this.s.options.w != null) ops.w = this.s.options.w;
    if(this.s.options.j != null) ops.j = this.s.options.j;
    if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync;
    if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout;
    return ops;
  }
});

/**
 * The callback format for the Db.open method
 * @callback Db~openCallback
 * @param {MongoError} error An error instance representing the error during the execution.
 * @param {Db} db The Db instance if the open method was successful.
 */

// Internal method
var open = function(self, callback) {
  self.s.topology.connect(self, self.s.options, function(err) {
    if(callback == null) return;
    var internalCallback = callback;
    callback == null;

    if(err) {
      self.close();
      return internalCallback(err);
    }

    internalCallback(null, self);
  });
}

/**
 * Open the database
 * @method
 * @param {Db~openCallback} [callback] Callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.open = function(callback) {
  var self = this;
  // We provided a callback leg
  if(typeof callback == 'function') return open(self, callback);
  // Return promise
  return new self.s.promiseLibrary(function(resolve, reject) {
    open(self, function(err, db) {
      if(err) return reject(err);
      resolve(db);
    })
  });
}

define.classMethod('open', {callback: true, promise:true});

/**
 * Converts provided read preference to CoreReadPreference
 * @param {(ReadPreference|string|object)} readPreference the user provided read preference
 * @return {CoreReadPreference}
 */
var convertReadPreference = function(readPreference) {
  if(readPreference &amp;&amp; typeof readPreference == 'string') {
    return new CoreReadPreference(readPreference);
  } else if(readPreference instanceof ReadPreference) {
    return new CoreReadPreference(readPreference.mode, readPreference.tags, {maxStalenessSeconds: readPreference.maxStalenessSeconds});
  } else if(readPreference &amp;&amp; typeof readPreference == 'object') {
    var mode = readPreference.mode || readPreference.preference;
    if (mode &amp;&amp; typeof mode == 'string') {
      readPreference = new CoreReadPreference(mode, readPreference.tags, {maxStalenessSeconds: readPreference.maxStalenessSeconds});
    }
  }
  return readPreference;
}

/**
 * The callback format for results
 * @callback Db~resultCallback
 * @param {MongoError} error An error instance representing the error during the execution.
 * @param {object} result The result object if the command was executed successfully.
 */

var executeCommand = function(self, command, options, callback) {
  // Did the user destroy the topology
  if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
  // Get the db name we are executing against
  var dbName = options.dbName || options.authdb || self.s.databaseName;

  // If we have a readPreference set
  if(options.readPreference == null &amp;&amp; self.s.readPreference) {
    options.readPreference = self.s.readPreference;
  }

  // Convert the readPreference if its not a write
  if(options.readPreference) {
    options.readPreference = convertReadPreference(options.readPreference);
  } else {
    options.readPreference = CoreReadPreference.primary;
  }

  // Debug information
  if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command %s against %s with options [%s]'
    , JSON.stringify(command), f('%s.$cmd', dbName), JSON.stringify(debugOptions(debugFields, options))));

  // Execute command
  self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) {
    if(err) return handleCallback(callback, err);
    if(options.full) return handleCallback(callback, null, result);
    handleCallback(callback, null, result.result);
  });
}

/**
 * Execute a command
 * @method
 * @param {object} command The command hash
 * @param {object} [options=null] Optional settings.
 * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
 * @param {Db~resultCallback} [callback] The command result callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.command = function(command, options, callback) {
  var self = this;
  // Change the callback
  if(typeof options == 'function') callback = options, options = {};
  // Clone the options
  options = shallowClone(options);

  // Do we have a callback
  if(typeof callback == 'function') return executeCommand(self, command, options, callback);
  // Return a promise
  return new this.s.promiseLibrary(function(resolve, reject) {
    executeCommand(self, command, options, function(err, r) {
      if(err) return reject(err);
      resolve(r);
    });
  });
}

define.classMethod('command', {callback: true, promise:true});

/**
 * The callback format for results
 * @callback Db~noResultCallback
 * @param {MongoError} error An error instance representing the error during the execution.
 * @param {null} result Is not set to a value
 */

/**
 * Close the db and its underlying connections
 * @method
 * @param {boolean} force Force close, emitting no events
 * @param {Db~noResultCallback} [callback] The result callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.close = function(force, callback) {
  if(typeof force == 'function') callback = force, force = false;
  this.s.topology.close(force);
  var self = this;

  // Fire close event if any listeners
  if(this.listeners('close').length > 0) {
    this.emit('close');

    // If it's the top level db emit close on all children
    if(this.parentDb == null) {
      // Fire close on all children
      for(var i = 0; i &lt; this.s.children.length; i++) {
        this.s.children[i].emit('close');
      }
    }

    // Remove listeners after emit
    self.removeAllListeners('close');
  }

  // Close parent db if set
  if(this.s.parentDb) this.s.parentDb.close();
  // Callback after next event loop tick
  if(typeof callback == 'function') return process.nextTick(function() {
    handleCallback(callback, null);
  })

  // Return dummy promise
  return new this.s.promiseLibrary(function(resolve) {
    resolve();
  });
}

define.classMethod('close', {callback: true, promise:true});

/**
 * Return the Admin db instance
 * @method
 * @return {Admin} return the new Admin db instance
 */
Db.prototype.admin = function() {
  return new Admin(this, this.s.topology, this.s.promiseLibrary);
};

define.classMethod('admin', {callback: false, promise:false, returns: [Admin]});

/**
 * The callback format for the collection method, must be used if strict is specified
 * @callback Db~collectionResultCallback
 * @param {MongoError} error An error instance representing the error during the execution.
 * @param {Collection} collection The collection instance.
 */

var collectionKeys = ['pkFactory', 'readPreference'
  , 'serializeFunctions', 'strict', 'readConcern', 'ignoreUndefined', 'promoteValues', 'promoteBuffers', 'promoteLongs'];

/**
 * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can
 * can use it without a callback in the following way: `var collection = db.collection('mycollection');`
 *
 * @method
 * @param {string} name the collection name we wish to access.
 * @param {object} [options=null] Optional settings.
 * @param {(number|string)} [options.w=null] The write concern.
 * @param {number} [options.wtimeout=null] The write concern timeout.
 * @param {boolean} [options.j=false] Specify a journal write concern.
 * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
 * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys.
 * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
 * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
 * @param {boolean} [options.strict=false] Returns an error if the collection does not exist
 * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported)
 * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported)
 * @param {Db~collectionResultCallback} callback The collection result callback
 * @return {Collection} return the new Collection instance if not in strict mode
 */
Db.prototype.collection = function(name, options, callback) {
  var self = this;
  if(typeof options == 'function') callback = options, options = {};
  options = options || {};
  options = shallowClone(options);
  // Set the promise library
  options.promiseLibrary = this.s.promiseLibrary;

  // If we have not set a collection level readConcern set the db level one
  options.readConcern = options.readConcern || this.s.readConcern;

  // Do we have ignoreUndefined set
  if(this.s.options.ignoreUndefined) {
    options.ignoreUndefined = this.s.options.ignoreUndefined;
  }

  // Merge in all needed options and ensure correct writeConcern merging from db level
  options = mergeOptionsAndWriteConcern(options, this.s.options, collectionKeys, true);

  // Execute
  if(options == null || !options.strict) {
    try {
      var collection = new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options);
      if(callback) callback(null, collection);
      return collection;
    } catch(err) {
      // if(err instanceof MongoError &amp;&amp; callback) return callback(err);
      if(callback) return callback(err);
      throw err;
    }
  }

  // Strict mode
  if(typeof callback != 'function') {
    throw toError(f("A callback is required in strict mode. While getting collection %s.", name));
  }

  // Did the user destroy the topology
  if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) {
    return callback(new MongoError('topology was destroyed'));
  }

  // Strict mode
  this.listCollections({name:name}, options).toArray(function(err, collections) {
    if(err != null) return handleCallback(callback, err, null);
    if(collections.length == 0) return handleCallback(callback, toError(f("Collection %s does not exist. Currently in strict mode.", name)), null);

    try {
      return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options));
    } catch(err) {
      return handleCallback(callback, err, null);
    }
  });
}

define.classMethod('collection', {callback: true, promise:false, returns: [Collection]});

function decorateWithWriteConcern(command, self, options) {
  // Do we support write concerns 3.4 and higher
  if(self.s.topology.capabilities().commandsTakeWriteConcern) {
    // Get the write concern settings
    var finalOptions = writeConcern(shallowClone(options), self, options);
    // Add the write concern to the command
    if(finalOptions.writeConcern) {
      command.writeConcern = finalOptions.writeConcern;
    }
  }
}

var createCollection = function(self, name, options, callback) {
  // Get the write concern options
  var finalOptions = writeConcern(shallowClone(options), self, options);
  // Did the user destroy the topology
  if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
  // Check if we have the name
  self.listCollections({name: name})
    .setReadPreference(ReadPreference.PRIMARY)
    .toArray(function(err, collections) {
      if(err != null) return handleCallback(callback, err, null);
      if(collections.length > 0 &amp;&amp; finalOptions.strict) {
        return handleCallback(callback, MongoError.create({message: f("Collection %s already exists. Currently in strict mode.", name), driver:true}), null);
      } else if (collections.length > 0) {
        try { return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); }
        catch(err) { return handleCallback(callback, err); }
      }

      // Create collection command
      var cmd = {'create':name};

      // Decorate command with writeConcern if supported
      decorateWithWriteConcern(cmd, self, options);
      // Add all optional parameters
      for(var n in options) {
        if(options[n] != null
          &amp;&amp; typeof options[n] != 'function' &amp;&amp; illegalCommandFields.indexOf(n) == -1) {
            cmd[n] = options[n];
        }
      }

      // Force a primary read Preference
      finalOptions.readPreference = ReadPreference.PRIMARY;

      // Execute command
      self.command(cmd, finalOptions, function(err) {
        if(err) return handleCallback(callback, err);
        handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options));
      });
  });
}

/**
 * Create a new collection on a server with the specified options. Use this to create capped collections.
 * More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/
 *
 * @method
 * @param {string} name the collection name we wish to access.
 * @param {object} [options=null] Optional settings.
 * @param {(number|string)} [options.w=null] The write concern.
 * @param {number} [options.wtimeout=null] The write concern timeout.
 * @param {boolean} [options.j=false] Specify a journal write concern.
 * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
 * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys.
 * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
 * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
 * @param {boolean} [options.strict=false] Returns an error if the collection does not exist
 * @param {boolean} [options.capped=false] Create a capped collection.
 * @param {boolean} [options.autoIndexId=true] Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version &lt; 2.2.
 * @param {number} [options.size=null] The size of the capped collection in bytes.
 * @param {number} [options.max=null] The maximum number of documents in the capped collection.
 * @param {number} [options.flags=null] Optional. Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag.
 * @param {object} [options.storageEngine=null] Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection on MongoDB 3.0 or higher.
 * @param {object} [options.validator=null] Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation on MongoDB 3.2 or higher.
 * @param {string} [options.validationLevel=null] Determines how strictly MongoDB applies the validation rules to existing documents during an update on MongoDB 3.2 or higher.
 * @param {string} [options.validationAction=null] Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted on MongoDB 3.2 or higher.
 * @param {object} [options.indexOptionDefaults=null] Allows users to specify a default configuration for indexes when creating a collection on MongoDB 3.2 or higher.
 * @param {string} [options.viewOn=null] The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create on MongoDB 3.4 or higher.
 * @param {array} [options.pipeline=null] An array that consists of the aggregation pipeline stage. create creates the view by applying the specified pipeline to the viewOn collection or view on MongoDB 3.4 or higher.
 * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
 * @param {Db~collectionResultCallback} [callback] The results callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.createCollection = function(name, options, callback) {
  var self = this;
  var args = Array.prototype.slice.call(arguments, 0);
  callback = args.pop();
  if(typeof callback != 'function') args.push(callback);
  name = args.length ? args.shift() : null;
  options = args.length ? args.shift() || {} : {};

  // Do we have a promisesLibrary
  options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary;

  // Check if the callback is in fact a string
  if(typeof callback == 'string') name = callback;

  // Execute the fallback callback
  if(typeof callback == 'function') return createCollection(self, name, options, callback);
  return new this.s.promiseLibrary(function(resolve, reject) {
    createCollection(self, name, options, function(err, r) {
      if(err) return reject(err);
      resolve(r);
    });
  });
}

define.classMethod('createCollection', {callback: true, promise:true});

/**
 * Get all the db statistics.
 *
 * @method
 * @param {object} [options=null] Optional settings.
 * @param {number} [options.scale=null] Divide the returned sizes by scale value.
 * @param {Db~resultCallback} [callback] The collection result callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.stats = function(options, callback) {
  if(typeof options == 'function') callback = options, options = {};
  options = options || {};
  // Build command object
  var commandObject = { dbStats:true };
  // Check if we have the scale value
  if(options['scale'] != null) commandObject['scale'] = options['scale'];

  // If we have a readPreference set
  if(options.readPreference == null &amp;&amp; this.s.readPreference) {
    options.readPreference = this.s.readPreference;
  }

  // Execute the command
  return this.command(commandObject, options, callback);
}

define.classMethod('stats', {callback: true, promise:true});

// Transformation methods for cursor results
var listCollectionsTranforms = function(databaseName) {
  var matching = f('%s.', databaseName);

  return {
    doc: function(doc) {
      var index = doc.name.indexOf(matching);
      // Remove database name if available
      if(doc.name &amp;&amp; index == 0) {
        doc.name = doc.name.substr(index + matching.length);
      }

      return doc;
    }
  }
}

/**
 * Get the list of all collection information for the specified db.
 *
 * @method
 * @param {object} [filter={}] Query to filter collections by
 * @param {object} [options=null] Optional settings.
 * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
 * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
 * @return {CommandCursor}
 */
Db.prototype.listCollections = function(filter, options) {
  filter = filter || {};
  options = options || {};

  // Shallow clone the object
  options = shallowClone(options);
  // Set the promise library
  options.promiseLibrary = this.s.promiseLibrary;

  // Ensure valid readPreference
  if(options.readPreference) {
    options.readPreference = convertReadPreference(options.readPreference);
  } else {
    options.readPreference = this.s.readPreference || CoreReadPreference.primary;
  }

  // We have a list collections command
  if(this.serverConfig.capabilities().hasListCollectionsCommand) {
    // Cursor options
    var cursor = options.batchSize ? {batchSize: options.batchSize} : {}
    // Build the command
    var command = { listCollections : true, filter: filter, cursor: cursor };
    // Set the AggregationCursor constructor
    options.cursorFactory = CommandCursor;
    // Create the cursor
    cursor = this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options);
    // Do we have a readPreference, apply it
    if(options.readPreference) {
      cursor.setReadPreference(options.readPreference);
    }
    // Return the cursor
    return cursor;
  }

  // We cannot use the listCollectionsCommand
  if(!this.serverConfig.capabilities().hasListCollectionsCommand) {
    // If we have legacy mode and have not provided a full db name filter it
    if(typeof filter.name == 'string' &amp;&amp; !(new RegExp('^' + this.databaseName + '\\.').test(filter.name))) {
      filter = shallowClone(filter);
      filter.name = f('%s.%s', this.s.databaseName, filter.name);
    }
  }

  // No filter, filter by current database
  if(filter == null) {
    filter.name = f('/%s/', this.s.databaseName);
  }

  // Rewrite the filter to use $and to filter out indexes
  if(filter.name) {
    filter = {$and: [{name: filter.name}, {name:/^((?!\$).)*$/}]};
  } else {
    filter = {name:/^((?!\$).)*$/};
  }

  // Return options
  var _options = {transforms: listCollectionsTranforms(this.s.databaseName)}
  // Get the cursor
  cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, _options);
  // Do we have a readPreference, apply it
  if(options.readPreference) cursor.setReadPreference(options.readPreference);
  // Set the passed in batch size if one was provided
  if(options.batchSize) cursor = cursor.batchSize(options.batchSize);
  // We have a fallback mode using legacy systems collections
  return cursor;
};

define.classMethod('listCollections', {callback: false, promise:false, returns: [CommandCursor]});

var evaluate = function(self, code, parameters, options, callback) {
  var finalCode = code;
  var finalParameters = [];

  // Did the user destroy the topology
  if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));

  // If not a code object translate to one
  if(!(finalCode &amp;&amp; finalCode._bsontype == 'Code')) finalCode = new Code(finalCode);
  // Ensure the parameters are correct
  if(parameters != null &amp;&amp; !Array.isArray(parameters) &amp;&amp; typeof parameters !== 'function') {
    finalParameters = [parameters];
  } else if(parameters != null &amp;&amp; Array.isArray(parameters) &amp;&amp; typeof parameters !== 'function') {
    finalParameters = parameters;
  }

  // Create execution selector
  var cmd = {'$eval':finalCode, 'args':finalParameters};
  // Check if the nolock parameter is passed in
  if(options['nolock']) {
    cmd['nolock'] = options['nolock'];
  }

  // Set primary read preference
  options.readPreference = new CoreReadPreference(ReadPreference.PRIMARY);

  // Execute the command
  self.command(cmd, options, function(err, result) {
    if(err) return handleCallback(callback, err, null);
    if(result &amp;&amp; result.ok == 1) return handleCallback(callback, null, result.retval);
    if(result) return handleCallback(callback, MongoError.create({message: f("eval failed: %s", result.errmsg), driver:true}), null);
    handleCallback(callback, err, result);
  });
}

/**
 * Evaluate JavaScript on the server
 *
 * @method
 * @param {Code} code JavaScript to execute on server.
 * @param {(object|array)} parameters The parameters for the call.
 * @param {object} [options=null] Optional settings.
 * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaluation of the javascript.
 * @param {Db~resultCallback} [callback] The results callback
 * @deprecated Eval is deprecated on MongoDB 3.2 and forward
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.eval = function(code, parameters, options, callback) {
  var self = this;
  var args = Array.prototype.slice.call(arguments, 1);
  callback = args.pop();
  if(typeof callback != 'function') args.push(callback);
  parameters = args.length ? args.shift() : parameters;
  options = args.length ? args.shift() || {} : {};

  // Check if the callback is in fact a string
  if(typeof callback == 'function') return evaluate(self, code, parameters, options, callback);
  // Execute the command
  return new this.s.promiseLibrary(function(resolve, reject) {
    evaluate(self, code, parameters, options, function(err, r) {
      if(err) return reject(err);
      resolve(r);
    });
  });
};

define.classMethod('eval', {callback: true, promise:true});

/**
 * Rename a collection.
 *
 * @method
 * @param {string} fromCollection Name of current collection to rename.
 * @param {string} toCollection New name of of the collection.
 * @param {object} [options=null] Optional settings.
 * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists.
 * @param {Db~collectionResultCallback} [callback] The results callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) {
  var self = this;
  if(typeof options == 'function') callback = options, options = {};
  options = options || {};
  // Add return new collection
  options.new_collection = true;

  // Check if the callback is in fact a string
  if(typeof callback == 'function') {
    return this.collection(fromCollection).rename(toCollection, options, callback);
  }

  // Return a promise
  return new this.s.promiseLibrary(function(resolve, reject) {
    self.collection(fromCollection).rename(toCollection, options, function(err, r) {
      if(err) return reject(err);
      resolve(r);
    });
  });
};

define.classMethod('renameCollection', {callback: true, promise:true});

/**
 * Drop a collection from the database, removing it permanently. New accesses will create a new collection.
 *
 * @method
 * @param {string} name Name of collection to drop
 * @param {Db~resultCallback} [callback] The results callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.dropCollection = function(name, options, callback) {
  var self = this;
  if(typeof options == 'function') callback = options, options = {};
  options = options || {};

  // Command to execute
  var cmd = {'drop':name}

  // Decorate with write concern
  decorateWithWriteConcern(cmd, self, options);

  // options
  options = assign({}, this.s.options, {readPreference: ReadPreference.PRIMARY});

  // Check if the callback is in fact a string
  if(typeof callback == 'function') return this.command(cmd, options, function(err, result) {
    // Did the user destroy the topology
    if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
    if(err) return handleCallback(callback, err);
    if(result.ok) return handleCallback(callback, null, true);
    handleCallback(callback, null, false);
  });

  // Clone the options
  options = shallowClone(self.s.options);
  // Set readPreference PRIMARY
  options.readPreference = ReadPreference.PRIMARY;

  // Execute the command
  return new this.s.promiseLibrary(function(resolve, reject) {
    // Execute command
    self.command(cmd, options, function(err, result) {
      // Did the user destroy the topology
      if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed'));
      if(err) return reject(err);
      if(result.ok) return resolve(true);
      resolve(false);
    });
  });
};

define.classMethod('dropCollection', {callback: true, promise:true});

/**
 * Drop a database, removing it permanently from the server.
 *
 * @method
 * @param {Db~resultCallback} [callback] The results callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.dropDatabase = function(options, callback) {
  var self = this;
  if(typeof options == 'function') callback = options, options = {};
  options = options || {};
  // Drop database command
  var cmd = {'dropDatabase':1};

  // Decorate with write concern
  decorateWithWriteConcern(cmd, self, options);

  // Ensure primary only
  options = assign({}, this.s.options, {readPreference: ReadPreference.PRIMARY});

  // Check if the callback is in fact a string
  if(typeof callback == 'function') return this.command(cmd, options, function(err, result) {
    // Did the user destroy the topology
    if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
    if(callback == null) return;
    if(err) return handleCallback(callback, err, null);
    handleCallback(callback, null, result.ok ? true : false);
  });

  // Execute the command
  return new this.s.promiseLibrary(function(resolve, reject) {
    // Execute command
    self.command(cmd, options, function(err, result) {
      // Did the user destroy the topology
      if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed'));
      if(err) return reject(err);
      if(result.ok) return resolve(true);
      resolve(false);
    });
  });
}

define.classMethod('dropDatabase', {callback: true, promise:true});

/**
 * The callback format for the collections method.
 * @callback Db~collectionsResultCallback
 * @param {MongoError} error An error instance representing the error during the execution.
 * @param {Collection[]} collections An array of all the collections objects for the db instance.
 */
var collections = function(self, callback) {
  // Let's get the collection names
  self.listCollections().toArray(function(err, documents) {
    if(err != null) return handleCallback(callback, err, null);
    // Filter collections removing any illegal ones
    documents = documents.filter(function(doc) {
      return doc.name.indexOf('$') == -1;
    });

    // Return the collection objects
    handleCallback(callback, null, documents.map(function(d) {
      return new Collection(self, self.s.topology, self.s.databaseName, d.name, self.s.pkFactory, self.s.options);
    }));
  });
}

/**
 * Fetch all collections for the current db.
 *
 * @method
 * @param {Db~collectionsResultCallback} [callback] The results callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.collections = function(callback) {
  var self = this;

  // Return the callback
  if(typeof callback == 'function') return collections(self, callback);
  // Return the promise
  return new self.s.promiseLibrary(function(resolve, reject) {
    collections(self, function(err, r) {
      if(err) return reject(err);
      resolve(r);
    });
  });
};

define.classMethod('collections', {callback: true, promise:true});

/**
 * Runs a command on the database as admin.
 * @method
 * @param {object} command The command hash
 * @param {object} [options=null] Optional settings.
 * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
 * @param {Db~resultCallback} [callback] The command result callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.executeDbAdminCommand = function(selector, options, callback) {
  var self = this;
  if(typeof options == 'function') callback = options, options = {};
  options = options || {};

  // Return the callback
  if(typeof callback == 'function') {
    // Convert read preference
    if(options.readPreference) {
      options.readPreference = convertReadPreference(options.readPreference)
    }

    return self.s.topology.command('admin.$cmd', selector, options, function(err, result) {
      // Did the user destroy the topology
      if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
      if(err) return handleCallback(callback, err);
      handleCallback(callback, null, result.result);
    });
  }

  // Return promise
  return new self.s.promiseLibrary(function(resolve, reject) {
    self.s.topology.command('admin.$cmd', selector, options, function(err, result) {
      // Did the user destroy the topology
      if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return reject(new MongoError('topology was destroyed'));
      if(err) return reject(err);
      resolve(result.result);
    });
  });
};

define.classMethod('executeDbAdminCommand', {callback: true, promise:true});

/**
 * Creates an index on the db and collection collection.
 * @method
 * @param {string} name Name of the collection to create the index on.
 * @param {(string|object)} fieldOrSpec Defines the index.
 * @param {object} [options=null] Optional settings.
 * @param {(number|string)} [options.w=null] The write concern.
 * @param {number} [options.wtimeout=null] The write concern timeout.
 * @param {boolean} [options.j=false] Specify a journal write concern.
 * @param {boolean} [options.unique=false] Creates an unique index.
 * @param {boolean} [options.sparse=false] Creates a sparse index.
 * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
 * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
 * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates.
 * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates.
 * @param {number} [options.v=null] Specify the format version of the indexes.
 * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
 * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
 * @param {object} [options.partialFilterExpression=null] Creates a partial index based on the given filter object (MongoDB 3.2 or higher)
 * @param {Db~resultCallback} [callback] The command result callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) {
  var self = this;
  var args = Array.prototype.slice.call(arguments, 2);
  callback = args.pop();
  if(typeof callback != 'function') args.push(callback);
  options = args.length ? args.shift() || {} : {};
  options = typeof callback === 'function' ? options : callback;
  options = options == null ? {} : options;
  // Shallow clone the options
  options = shallowClone(options);

  // If we have a callback fallback
  if(typeof callback == 'function') return createIndex(self, name, fieldOrSpec, options, callback);
  // Return a promise
  return new this.s.promiseLibrary(function(resolve, reject) {
    createIndex(self, name, fieldOrSpec, options, function(err, r) {
      if(err) return reject(err);
      resolve(r);
    });
  });
};

var createIndex = function(self, name, fieldOrSpec, options, callback) {
  // Get the write concern options
  var finalOptions = writeConcern({}, self, options, { readPreference: ReadPreference.PRIMARY });
  // Ensure we have a callback
  if(finalOptions.writeConcern &amp;&amp; typeof callback != 'function') {
    throw MongoError.create({message: "Cannot use a writeConcern without a provided callback", driver:true});
  }

  // Run only against primary
  options.readPreference = ReadPreference.PRIMARY;

  // Did the user destroy the topology
  if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));

  // Attempt to run using createIndexes command
  createIndexUsingCreateIndexes(self, name, fieldOrSpec, options, function(err, result) {
    if(err == null) return handleCallback(callback, err, result);

    // 67 = 'CannotCreateIndex' (malformed index options)
    // 85 = 'IndexOptionsConflict' (index already exists with different options)
    // 11000 = 'DuplicateKey' (couldn't build unique index because of dupes)
    // 11600 = 'InterruptedAtShutdown' (interrupted at shutdown)
    // These errors mean that the server recognized `createIndex` as a command
    // and so we don't need to fallback to an insert.
    if(err.code === 67 || err.code == 11000 || err.code === 85 || err.code == 11600) {
      return handleCallback(callback, err, result);
    }

    // Create command
    var doc = createCreateIndexCommand(self, name, fieldOrSpec, options);
    // Set no key checking
    finalOptions.checkKeys = false;
    // Insert document
    self.s.topology.insert(f("%s.%s", self.s.databaseName, Db.SYSTEM_INDEX_COLLECTION), doc, finalOptions, function(err, result) {
      if(callback == null) return;
      if(err) return handleCallback(callback, err);
      if(result == null) return handleCallback(callback, null, null);
      if(result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null);
      handleCallback(callback, null, doc.name);
    });
  });
}

define.classMethod('createIndex', {callback: true, promise:true});

/**
 * Ensures that an index exists, if it does not it creates it
 * @method
 * @deprecated since version 2.0
 * @param {string} name The index name
 * @param {(string|object)} fieldOrSpec Defines the index.
 * @param {object} [options=null] Optional settings.
 * @param {(number|string)} [options.w=null] The write concern.
 * @param {number} [options.wtimeout=null] The write concern timeout.
 * @param {boolean} [options.j=false] Specify a journal write concern.
 * @param {boolean} [options.unique=false] Creates an unique index.
 * @param {boolean} [options.sparse=false] Creates a sparse index.
 * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
 * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
 * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates.
 * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates.
 * @param {number} [options.v=null] Specify the format version of the indexes.
 * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
 * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
 * @param {Db~resultCallback} [callback] The command result callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.ensureIndex = function(name, fieldOrSpec, options, callback) {
  var self = this;
  if(typeof options == 'function') callback = options, options = {};
  options = options || {};

  // If we have a callback fallback
  if(typeof callback == 'function') return ensureIndex(self, name, fieldOrSpec, options, callback);

  // Return a promise
  return new this.s.promiseLibrary(function(resolve, reject) {
    ensureIndex(self, name, fieldOrSpec, options, function(err, r) {
      if(err) return reject(err);
      resolve(r);
    });
  });
};

var ensureIndex = function(self, name, fieldOrSpec, options, callback) {
  // Get the write concern options
  var finalOptions = writeConcern({}, self, options);
  // Create command
  var selector = createCreateIndexCommand(self, name, fieldOrSpec, options);
  var index_name = selector.name;

  // Did the user destroy the topology
  if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));

  // Merge primary readPreference
  finalOptions.readPreference = ReadPreference.PRIMARY

  // Check if the index already exists
  self.indexInformation(name, finalOptions, function(err, indexInformation) {
    if(err != null &amp;&amp; err.code != 26) return handleCallback(callback, err, null);
    // If the index does not exist, create it
    if(indexInformation == null || !indexInformation[index_name])  {
      self.createIndex(name, fieldOrSpec, options, callback);
    } else {
      if(typeof callback === 'function') return handleCallback(callback, null, index_name);
    }
  });
}

define.classMethod('ensureIndex', {callback: true, promise:true});

Db.prototype.addChild = function(db) {
  if(this.s.parentDb) return this.s.parentDb.addChild(db);
  this.s.children.push(db);
}

/**
 * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are
 * related in a parent-child relationship to the original instance so that events are correctly emitted on child
 * db instances. Child db instances are cached so performing db('db1') twice will return the same instance.
 * You can control these behaviors with the options noListener and returnNonCachedInstance.
 *
 * @method
 * @param {string} name The name of the database we want to use.
 * @param {object} [options=null] Optional settings.
 * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection.
 * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created
 * @return {Db}
 */
Db.prototype.db = function(dbName, options) {
  options = options || {};

  // Copy the options and add out internal override of the not shared flag
  var finalOptions = assign({}, this.options, options);

  // Do we have the db in the cache already
  if(this.s.dbCache[dbName] &amp;&amp; finalOptions.returnNonCachedInstance !== true) {
    return this.s.dbCache[dbName];
  }

  // Add current db as parentDb
  if(finalOptions.noListener == null || finalOptions.noListener == false) {
    finalOptions.parentDb = this;
  }

  // Add promiseLibrary
  finalOptions.promiseLibrary = this.s.promiseLibrary;

  // Return the db object
  var db = new Db(dbName, this.s.topology, finalOptions)

  // Add as child
  if(finalOptions.noListener == null || finalOptions.noListener == false) {
    this.addChild(db);
  }

  // Add the db to the cache
  this.s.dbCache[dbName] = db;
  // Return the database
  return db;
};

define.classMethod('db', {callback: false, promise:false, returns: [Db]});

var _executeAuthCreateUserCommand = function(self, username, password, options, callback) {
  // Special case where there is no password ($external users)
  if(typeof username == 'string'
    &amp;&amp; password != null &amp;&amp; typeof password == 'object') {
    options = password;
    password = null;
  }

  // Unpack all options
  if(typeof options == 'function') {
    callback = options;
    options = {};
  }

  // Error out if we digestPassword set
  if(options.digestPassword != null) {
    throw toError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option.");
  }

  // Get additional values
  var customData = options.customData != null ? options.customData : {};
  var roles = Array.isArray(options.roles) ? options.roles : [];
  var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null;

  // If not roles defined print deprecated message
  if(roles.length == 0) {
    console.log("Creating a user without roles is deprecated in MongoDB >= 2.6");
  }

  // Get the error options
  var commandOptions = {writeCommand:true};
  if(options['dbName']) commandOptions.dbName = options['dbName'];

  // Add maxTimeMS to options if set
  if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS;

  // Check the db name and add roles if needed
  if((self.databaseName.toLowerCase() == 'admin' || options.dbName == 'admin') &amp;&amp; !Array.isArray(options.roles)) {
    roles = ['root']
  } else if(!Array.isArray(options.roles)) {
    roles = ['dbOwner']
  }

  // Build the command to execute
  var command = {
      createUser: username
    , customData: customData
    , roles: roles
    , digestPassword:false
  }

  // Apply write concern to command
  command = writeConcern(command, self, options);

  // Use node md5 generator
  var md5 = crypto.createHash('md5');
  // Generate keys used for authentication
  md5.update(username + ":mongo:" + password);
  var userPassword = md5.digest('hex');

  // No password
  if(typeof password == 'string') {
    command.pwd = userPassword;
  }

  // Force write using primary
  commandOptions.readPreference = ReadPreference.primary;

  // Execute the command
  self.command(command, commandOptions, function(err, result) {
    if(err &amp;&amp; err.ok == 0 &amp;&amp; err.code == undefined) return handleCallback(callback, {code: -5000}, null);
    if(err) return handleCallback(callback, err, null);
    handleCallback(callback, !result.ok ? toError(result) : null
      , result.ok ? [{user: username, pwd: ''}] : null);
  })
}

var addUser = function(self, username, password, options, callback) {
  // Did the user destroy the topology
  if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
  // Attempt to execute auth command
  _executeAuthCreateUserCommand(self, username, password, options, function(err, r) {
    // We need to perform the backward compatible insert operation
    if(err &amp;&amp; err.code == -5000) {
      var finalOptions = writeConcern(shallowClone(options), self, options);
      // Use node md5 generator
      var md5 = crypto.createHash('md5');
      // Generate keys used for authentication
      md5.update(username + ":mongo:" + password);
      var userPassword = md5.digest('hex');

      // If we have another db set
      var db = options.dbName ? self.db(options.dbName) : self;

      // Fetch a user collection
      var collection = db.collection(Db.SYSTEM_USER_COLLECTION);

      // Check if we are inserting the first user
      collection.count({}, function(err, count) {
        // We got an error (f.ex not authorized)
        if(err != null) return handleCallback(callback, err, null);
        // Check if the user exists and update i
        collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err) {
          // We got an error (f.ex not authorized)
          if(err != null) return handleCallback(callback, err, null);
          // Add command keys
          finalOptions.upsert = true;

          // We have a user, let's update the password or upsert if not
          collection.update({user: username},{$set: {user: username, pwd: userPassword}}, finalOptions, function(err) {
            if(count == 0 &amp;&amp; err) return handleCallback(callback, null, [{user:username, pwd:userPassword}]);
            if(err) return handleCallback(callback, err, null)
            handleCallback(callback, null, [{user:username, pwd:userPassword}]);
          });
        });
      });

      return;
    }

    if(err) return handleCallback(callback, err);
    handleCallback(callback, err, r);
  });
}

/**
 * Add a user to the database.
 * @method
 * @param {string} username The username.
 * @param {string} password The password.
 * @param {object} [options=null] Optional settings.
 * @param {(number|string)} [options.w=null] The write concern.
 * @param {number} [options.wtimeout=null] The write concern timeout.
 * @param {boolean} [options.j=false] Specify a journal write concern.
 * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher)
 * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher)
 * @param {Db~resultCallback} [callback] The command result callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.addUser = function(username, password, options, callback) {
  // Unpack the parameters
  var self = this;
  var args = Array.prototype.slice.call(arguments, 2);
  callback = args.pop();
  if(typeof callback != 'function') args.push(callback);
  options = args.length ? args.shift() || {} : {};

  // If we have a callback fallback
  if(typeof callback == 'function') return addUser(self, username, password, options, callback);

  // Return a promise
  return new this.s.promiseLibrary(function(resolve, reject) {
    addUser(self, username, password, options, function(err, r) {
      if(err) return reject(err);
      resolve(r);
    });
  });
};

define.classMethod('addUser', {callback: true, promise:true});

var _executeAuthRemoveUserCommand = function(self, username, options, callback) {
  if(typeof options == 'function') callback = options, options = {};
  // Did the user destroy the topology
  if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
  // Get the error options
  var commandOptions = {writeCommand:true};
  if(options['dbName']) commandOptions.dbName = options['dbName'];

  // Get additional values
  var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null;

  // Add maxTimeMS to options if set
  if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS;

  // Build the command to execute
  var command = {
    dropUser: username
  }

  // Apply write concern to command
  command = writeConcern(command, self, options);

  // Force write using primary
  commandOptions.readPreference = ReadPreference.primary;

  // Execute the command
  self.command(command, commandOptions, function(err, result) {
    if(err &amp;&amp; !err.ok &amp;&amp; err.code == undefined) return handleCallback(callback, {code: -5000});
    if(err) return handleCallback(callback, err, null);
    handleCallback(callback, null, result.ok ? true : false);
  })
}

var removeUser = function(self, username, options, callback) {
  // Attempt to execute command
  _executeAuthRemoveUserCommand(self, username, options, function(err, result) {
    if(err &amp;&amp; err.code == -5000) {
      var finalOptions = writeConcern(shallowClone(options), self, options);
      // If we have another db set
      var db = options.dbName ? self.db(options.dbName) : self;

      // Fetch a user collection
      var collection = db.collection(Db.SYSTEM_USER_COLLECTION);

      // Locate the user
      collection.findOne({user: username}, {}, function(err, user) {
        if(user == null) return handleCallback(callback, err, false);
        collection.remove({user: username}, finalOptions, function(err) {
          handleCallback(callback, err, true);
        });
      });

      return;
    }

    if(err) return handleCallback(callback, err);
    handleCallback(callback, err, result);
  });
}

define.classMethod('removeUser', {callback: true, promise:true});

/**
 * Remove a user from a database
 * @method
 * @param {string} username The username.
 * @param {object} [options=null] Optional settings.
 * @param {(number|string)} [options.w=null] The write concern.
 * @param {number} [options.wtimeout=null] The write concern timeout.
 * @param {boolean} [options.j=false] Specify a journal write concern.
 * @param {Db~resultCallback} [callback] The command result callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.removeUser = function(username, options, callback) {
  // Unpack the parameters
  var self = this;
  var args = Array.prototype.slice.call(arguments, 1);
  callback = args.pop();
  if(typeof callback != 'function') args.push(callback);
  options = args.length ? args.shift() || {} : {};

  // If we have a callback fallback
  if(typeof callback == 'function') return removeUser(self, username, options, callback);

  // Return a promise
  return new this.s.promiseLibrary(function(resolve, reject) {
    removeUser(self, username, options, function(err, r) {
      if(err) return reject(err);
      resolve(r);
    });
  });
};

/**
 * Authenticate a user against the server.
 * @method
 * @param {string} username The username.
 * @param {string} [password] The password.
 * @param {object} [options=null] Optional settings.
 * @param {string} [options.authMechanism=MONGODB-CR] The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN
 * @param {Db~resultCallback} [callback] The command result callback
 * @return {Promise} returns Promise if no callback passed
 * @deprecated This method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.
 */
Db.prototype.authenticate = function(username, password, options, callback) {
  console.warn("Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.");
  return authenticate.apply(this, [this].concat(Array.prototype.slice.call(arguments)));
};

define.classMethod('authenticate', {callback: true, promise:true});

/**
 * Logout user from server, fire off on all connections and remove all auth info
 * @method
 * @param {object} [options=null] Optional settings.
 * @param {string} [options.dbName=null] Logout against different database than current.
 * @param {Db~resultCallback} [callback] The command result callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.logout = function(options, callback) {
  var self = this;
  if(typeof options == 'function') callback = options, options = {};
  options = options || {};

  // Establish the correct database name
  var dbName = this.s.authSource ? this.s.authSource : this.s.databaseName;
  dbName = options.dbName ? options.dbName : dbName;

  // If we have a callback
  if(typeof callback == 'function') {
    return self.s.topology.logout(dbName, function(err) {
      if(err) return callback(err);
      callback(null, true);
    });
  }

  // Return a promise
  return new this.s.promiseLibrary(function(resolve, reject) {
    self.s.topology.logout(dbName, function(err) {
      if(err) return reject(err);
      resolve(true);
    });
  });
}

define.classMethod('logout', {callback: true, promise:true});

/**
 * Retrieves this collections index info.
 * @method
 * @param {string} name The name of the collection.
 * @param {object} [options=null] Optional settings.
 * @param {boolean} [options.full=false] Returns the full raw index information.
 * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
 * @param {Db~resultCallback} [callback] The command result callback
 * @return {Promise} returns Promise if no callback passed
 */
Db.prototype.indexInformation = function(name, options, callback) {
  var self = this;
  if(typeof options == 'function') callback = options, options = {};
  options = options || {};

  // If we have a callback fallback
  if(typeof callback == 'function') return indexInformation(self, name, options, callback);

  // Return a promise
  return new this.s.promiseLibrary(function(resolve, reject) {
    indexInformation(self, name, options, function(err, r) {
      if(err) return reject(err);
      resolve(r);
    });
  });
};

var indexInformation = function(self, name, options, callback) {
    // If we specified full information
  var full = options['full'] == null ? false : options['full'];

  // Did the user destroy the topology
  if(self.serverConfig &amp;&amp; self.serverConfig.isDestroyed()) return callback(new MongoError('topology was destroyed'));
  // Process all the results from the index command and collection
  var processResults = function(indexes) {
    // Contains all the information
    var info = {};
    // Process all the indexes
    for(var i = 0; i &lt; indexes.length; i++) {
      var index = indexes[i];
      // Let's unpack the object
      info[index.name] = [];
      for(var name in index.key) {
        info[index.name].push([name, index.key[name]]);
      }
    }

    return info;
  }

  // Get the list of indexes of the specified collection
  self.collection(name).listIndexes(options).toArray(function(err, indexes) {
    if(err) return callback(toError(err));
    if(!Array.isArray(indexes)) return handleCallback(callback, null, []);
    if(full) return handleCallback(callback, null, indexes);
    handleCallback(callback, null, processResults(indexes));
  });
}

define.classMethod('indexInformation', {callback: true, promise:true});

var createCreateIndexCommand = function(db, name, fieldOrSpec, options) {
  var indexParameters = parseIndexOptions(fieldOrSpec);
  var fieldHash = indexParameters.fieldHash;

  // Generate the index name
  var indexName = typeof options.name == 'string' ? options.name : indexParameters.name;
  var selector = {
    'ns': db.databaseName + "." + name, 'key': fieldHash, 'name': indexName
  }

  // Ensure we have a correct finalUnique
  var finalUnique = options == null || 'object' === typeof options ? false : options;
  // Set up options
  options = options == null || typeof options == 'boolean' ? {} : options;

  // Add all the options
  var keysToOmit = Object.keys(selector);
  for(var optionName in options) {
    if(keysToOmit.indexOf(optionName) == -1) {
      selector[optionName] = options[optionName];
    }
  }

  if(selector['unique'] == null) selector['unique'] = finalUnique;

  // Remove any write concern operations
  var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference'];
  for(var i = 0; i &lt; removeKeys.length; i++) {
    delete selector[removeKeys[i]];
  }

  // Return the command creation selector
  return selector;
}

var createIndexUsingCreateIndexes = function(self, name, fieldOrSpec, options, callback) {
  // Build the index
  var indexParameters = parseIndexOptions(fieldOrSpec);
  // Generate the index name
  var indexName = typeof options.name == 'string' ? options.name : indexParameters.name;
  // Set up the index
  var indexes = [{ name: indexName, key: indexParameters.fieldHash }];
  // merge all the options
  var keysToOmit = Object.keys(indexes[0]);
  for(var optionName in options) {
    if(keysToOmit.indexOf(optionName) == -1) {
      indexes[0][optionName] = options[optionName];
    }

    // Remove any write concern operations
    var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference'];
    for(var i = 0; i &lt; removeKeys.length; i++) {
      delete indexes[0][removeKeys[i]];
    }
  }

  // Get capabilities
  var capabilities = self.s.topology.capabilities();

  // Did the user pass in a collation, check if our write server supports it
  if(indexes[0].collation &amp;&amp; capabilities &amp;&amp; !capabilities.commandsTakeCollation) {
    // Create a new error
    var error = new MongoError(f('server/primary/mongos does not support collation'));
    error.code = 67;
    // Return the error
    return callback(error);
  }

  // Create command, apply write concern to command
  var cmd = writeConcern({createIndexes: name, indexes: indexes}, self, options);

  // Decorate command with writeConcern if supported
  decorateWithWriteConcern(cmd, self, options);

  // ReadPreference primary
  options.readPreference = ReadPreference.PRIMARY;

  // Build the command
  self.command(cmd, options, function(err, result) {
    if(err) return handleCallback(callback, err, null);
    if(result.ok == 0) return handleCallback(callback, toError(result), null);
    // Return the indexName for backward compatibility
    handleCallback(callback, null, indexName);
  });
}

// Validate the database name
var validateDatabaseName = function(databaseName) {
  if(typeof databaseName !== 'string') throw MongoError.create({message: "database name must be a string", driver:true});
  if(databaseName.length === 0) throw MongoError.create({message: "database name cannot be the empty string", driver:true});
  if(databaseName == '$external') return;

  var invalidChars = [" ", ".", "$", "/", "\\"];
  for(var i = 0; i &lt; invalidChars.length; i++) {
    if(databaseName.indexOf(invalidChars[i]) != -1) throw MongoError.create({message: "database names cannot contain the character '" + invalidChars[i] + "'", driver:true});
  }
}

// Get write concern
var writeConcern = function(target, db, options) {
  if(options.w != null || options.j != null || options.fsync != null) {
    var opts = {};
    if(options.w) opts.w = options.w;
    if(options.wtimeout) opts.wtimeout = options.wtimeout;
    if(options.j) opts.j = options.j;
    if(options.fsync) opts.fsync = options.fsync;
    target.writeConcern = opts;
  } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) {
    target.writeConcern = db.writeConcern;
  }

  return target
}

// Add listeners to topology
var createListener = function(self, e, object) {
  var listener = function(err) {
    if(object.listeners(e).length > 0) {
      object.emit(e, err, self);

      // Emit on all associated db's if available
      for(var i = 0; i &lt; self.s.children.length; i++) {
        self.s.children[i].emit(e, err, self.s.children[i]);
      }
    }
  }
  return listener;
}


/**
 * Unref all sockets
 * @method
 */
Db.prototype.unref = function() {
  this.s.topology.unref();
}

/**
 * Db close event
 *
 * Emitted after a socket closed against a single server or mongos proxy.
 *
 * @event Db#close
 * @type {MongoError}
 */

/**
 * Db authenticated event
 *
 * Emitted after all server members in the topology (single server, replicaset or mongos) have successfully authenticated.
 *
 * @event Db#authenticated
 * @type {object}
 */

/**
 * Db reconnect event
 *
 *  * Server: Emitted when the driver has reconnected and re-authenticated.
 *  * ReplicaSet: N/A
 *  * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos.
 *
 * @event Db#reconnect
 * @type {object}
 */

/**
 * Db error event
 *
 * Emitted after an error occurred against a single server or mongos proxy.
 *
 * @event Db#error
 * @type {MongoError}
 */

/**
 * Db timeout event
 *
 * Emitted after a socket timeout occurred against a single server or mongos proxy.
 *
 * @event Db#timeout
 * @type {MongoError}
 */

/**
 * Db parseError event
 *
 * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server.
 *
 * @event Db#parseError
 * @type {MongoError}
 */

/**
 * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time.
 *
 * * Server: Emitted when the driver has connected to the single server and has authenticated.
 * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members.
 * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies.
 *
 * @event Db#fullsetup
 * @type {Db}
 */

// Constants
Db.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces";
Db.SYSTEM_INDEX_COLLECTION = "system.indexes";
Db.SYSTEM_PROFILE_COLLECTION = "system.profile";
Db.SYSTEM_USER_COLLECTION = "system.users";
Db.SYSTEM_COMMAND_COLLECTION = "$cmd";
Db.SYSTEM_JS_COLLECTION = "system.js";

module.exports = Db;
</code></pre>
        </article>
    </section>






                    <footer>
                        Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Mon Oct 01 2018 09:50:14 GMT-0400 (EDT)
                    </footer>
                </div>
            </td>
        </tr>
    </table>
</div>
<script>prettyPrint();</script>
<script src="scripts/linenumber.js"></script>
<script src="scripts/main.js"></script>
</body>
</html>
